Populating next right pointers in each node II
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
Solution 1
This question can still be easily solved using level traversal, and even the code can be exactly the same as a question. Populating next right pointers in each node total
But it does not meet the requirements of space complexity: constant extra space.
1 /** 2 * Definition for binary tree with next pointer. 3 * public class TreeLinkNode { 4 * int val; 5 * TreeLinkNode left, right, next; 6 * TreeLinkNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution {10 public void connect(TreeLinkNode root) {11 if (root == null) {12 return;13 }14 15 TreeLinkNode dummy = new TreeLinkNode(0);16 Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>();17 18 q.offer(root);19 q.offer(dummy);20 21 while(!q.isEmpty()) {22 TreeLinkNode cur = q.poll();23 if (cur == dummy) {24 if (!q.isEmpty()) {25 q.offer(dummy);26 }27 continue;28 }29 30 if (q.peek() == dummy) {31 cur.next = null;32 } else {33 cur.next = q.peek(); 34 }35 36 if (cur.left != null) {37 q.offer(cur.left);38 }39 40 if (cur.right != null) {41 q.offer(cur.right);42 }43 }44 45 }46 }
View code
Solution 2
We can use recursive solutions. Add next from right to left. Otherwise, the right side is not created, and you cannot find next on the left side. This calculation complies with the constant extra space.
1 public void connect(TreeLinkNode root) { 2 if (root == null) { 3 return; 4 } 5 6 TreeLinkNode cur = root.next; 7 TreeLinkNode next = null; 8 // this is very important. should exit after found the next. 9 while (cur != null && next == null) {10 if (cur.left != null) {11 next = cur.left;12 } else if (cur.right != null) {13 next = cur.right;14 } else {15 cur = cur.next;16 }17 }18 19 if (root.right != null) {20 root.right.next = next;21 next = root.right;22 }23 24 if (root.left != null) {25 root.left.next = next;26 }27 28 // The order is very important. We should deal with right first!29 connect(root.right);30 connect(root.left);31 }
View code
Leetcode: populating next right pointers in each node II solution report