Follow up for problem "populating next right pointers in each node ".
What if the given tree cocould be any binary tree? Wocould 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 shoshould look like:
1 -> NULL / 2 -> 3 -> NULL / \ 4-> 5 -> 7 -> NULL
An1_1:
public void connect(TreeLinkNode root) {if (null == root) {return;}TreeLinkNode cur = root.next;TreeLinkNode p = null;while (cur != null) { // find last right node (left or right)if (cur.left != null) {p = cur.left;break;}if (cur.right != null) {p = cur.right;break;}cur = cur.next;}if (root.right != null) {root.right.next = p;}if (root.left != null) {root.left.next = root.right != null ? root.right : p;}connect(root.right); // from right to leftconnect(root.left);}
Note:
1) list is a non-perfect binary tree, and the right branch may be empty. Therefore, traverse from right-> left
2) Find the right node from the rightmost branch and the root node does not have the left node.
An1_2:
public void connect(TreeLinkNode root) {if (null == root) {return;}LinkedList<TreeLinkNode> Q = new LinkedList<TreeLinkNode>(); // save one// line// root(s)LinkedList<TreeLinkNode> Q2 = new LinkedList<TreeLinkNode>();; // save next one line root(s), swap with QQ.push(root);while (!Q.isEmpty()) {TreeLinkNode tmp = Q.getFirst();Q.pop();if (tmp.left != null)Q2.add(tmp.left);if (tmp.right != null)Q2.add(tmp.right);if (Q.isEmpty()) {tmp.next = null;LinkedList<TreeLinkNode> tmpQ = Q; // swap queueQ = Q2;Q2 = tmpQ;} else {tmp.next = Q.getFirst();}}}Note:
1) Add a Q2 queue to save all the elements of the next row. If the auxiliary judgment is the last element (Q is empty), it is set to null.
2) queue implementation is better than Recursion
An1_3:
public void connect(TreeLinkNode root) {LinkedList<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();if (root == null)return;TreeLinkNode p;queue.add(root);queue.add(null);// flagwhile (!queue.isEmpty()) {p = queue.pop();if (p != null) {if (p.left != null) {queue.add(p.left);}if (p.right != null) {queue.add(p.right);}p.next = queue.getFirst();} else {if (queue.isEmpty()) {return;}queue.add(null);}}}
Leetcode 117 populating next right pointers in each node II