Problem Description:
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
For example,NULL
. We also need to use constant space.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 -> NULLSolution:
Use level order traversal.
public class Solution { public void connect(TreeLinkNode root) { while(root != null){ TreeLinkNode tempChild = new TreeLinkNode(0); TreeLinkNode currentChild = tempChild; while(root!=null){ if(root.left != null) { currentChild.next = root.left; currentChild = currentChild.next;} if(root.right != null) { currentChild.next = root.right; currentChild = currentChild.next;} root = root.next; } root = tempChild.next; } } }
No comments:
Post a Comment