Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example 1:
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Example 2:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 6000].
-100 <= Node.val <= 100
Follow-up:
You may only use constant extra space.
The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
Solutions
Solution 1: BFS
We use a queue $q$ for level order traversal. Each time we traverse a level, we connect the nodes of the current level in order.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.
/*// Definition for a Node.class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; }};*/classSolution{publicNodeconnect(Noderoot){if(root==null){returnroot;}Deque<Node>q=newArrayDeque<>();q.offer(root);while(!q.isEmpty()){Nodep=null;for(intn=q.size();n>0;--n){Nodenode=q.poll();if(p!=null){p.next=node;}p=node;if(node.left!=null){q.offer(node.left);}if(node.right!=null){q.offer(node.right);}}}returnroot;}}
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * Next *Node * } */funcconnect(root*Node)*Node{ifroot==nil{returnroot}q:=[]*Node{root}forlen(q)>0{varp*Nodeforn:=len(q);n>0;n--{node:=q[0]q=q[1:]ifp!=nil{p.Next=node}p=nodeifnode.Left!=nil{q=append(q,node.Left)}ifnode.Right!=nil{q=append(q,node.Right)}}}returnroot}
/*// Definition for a Node.public class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; }}*/publicclassSolution{publicNodeConnect(Noderoot){if(root==null){returnnull;}varq=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodep=null;for(inti=q.Count;i>0;--i){varnode=q.Dequeue();if(p!=null){p.next=node;}p=node;if(node.left!=null){q.Enqueue(node.left);}if(node.right!=null){q.Enqueue(node.right);}}}returnroot;}}
Solution 2: Space Optimization
The space complexity of Solution 1 is relatively high because it requires a queue to store the nodes of each level. We can implement it with constant space.
We define two pointers $prev$ and $next$, which point to the previous node and the first node of the next level, respectively. When traversing the nodes of the current level, we string the nodes of the next level together and find the first node of the next level. After the current level is traversed, we assign the first node $next$ of the next level to $node$ and continue to traverse.
The time complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. The space complexity is $O(1)$.
/*// Definition for a Node.class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; }};*/classSolution{privateNodeprev,next;publicNodeconnect(Noderoot){Nodenode=root;while(node!=null){prev=null;next=null;while(node!=null){modify(node.left);modify(node.right);node=node.next;}node=next;}returnroot;}privatevoidmodify(Nodecurr){if(curr==null){return;}if(next==null){next=curr;}if(prev!=null){prev.next=curr;}prev=curr;}}
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * Next *Node * } */funcconnect(root*Node)*Node{node:=rootvarprev,next*Nodemodify:=func(curr*Node){ifcurr==nil{return}ifnext==nil{next=curr}ifprev!=nil{prev.Next=curr}prev=curr}fornode!=nil{prev,next=nil,nilfornode!=nil{modify(node.Left)modify(node.Right)node=node.Next}node=next}returnroot}
/*// Definition for a Node.public class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; }}*/publicclassSolution{privateNodeprev,next;publicNodeConnect(Noderoot){Nodenode=root;while(node!=null){prev=null;next=null;while(node!=null){modify(node.left);modify(node.right);node=node.next;}node=next;}returnroot;}privatevoidmodify(Nodecurr){if(curr==null){return;}if(next==null){next=curr;}if(prev!=null){prev.next=curr;}prev=curr;}}