题目
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For 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
方法一
同样可以采用树的层次遍历,需要统计每一层的结点数量
public void connect(TreeLinkNode root) { if (root != null) { if (!(root.left == null && root.right == null)) { Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>(); int count = 0; if (root.left != null) { queue.offer(root.left); count++; } if (root.right != null) { queue.offer(root.right); count++; } while(!queue.isEmpty()) { int n = count; count = 0; TreeLinkNode pre = queue.poll(); if (pre.left != null) { queue.offer(pre.left); count++; } if (pre.right != null) { queue.offer(pre.right); count++; } for (int i = 1; i < n; i++) { TreeLinkNode cur = queue.poll(); if (cur.left != null) { queue.offer(cur.left); count++; } if (cur.right != null) { queue.offer(cur.right); count++; } pre.next = cur; pre = cur; } } } } }
方法二
利用next指针 进行遍历。
public void connect(TreeLinkNode root) { if (root != null) { TreeLinkNode nextNode = root.next; while(nextNode != null) { if (nextNode.left != null) { nextNode = nextNode.left; break; } if (nextNode.right != null) { nextNode = nextNode.right; break; } nextNode = nextNode.next; } if (root.right != null) { root.right.next = nextNode; } if (root.left != null) { root.left.next = (root.right != null ? root.right : nextNode); } connect(root.right); connect(root.left); } }