FFor example,
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
注意这道题应该先遍历右边然后再左边
时间O(n) 空间O(1)
public class Solution { public void connect(TreeLinkNode root) { if (root == null) { return; } TreeLinkNode tem = root.next; while (tem != null) { if (tem.left != null) { tem = tem.left; break; } else if (tem.right != null) { tem = tem.right; break; } else { tem = tem.next; } } if (root.right != null) { root.right.next = tem; } if (root.left != null) { if (root.right != null) { root.left.next = root.right; } else { root.left.next = tem; } } connect(root.right); connect(root.left); } }
没有评论:
发表评论