Given a binary tree
struct Treelinknode { treelinknode *left; Treelinknode *right; Treelinknode *next; }
Populate each of the next pointer to the next right node. If There is no next right node, the next pointer should are set to NULL .
Initially, all next pointers is set to NULL .
Note:
- Constant extra space.
- You could assume that it was a perfect binary tree (ie, all leaves was at the same level, and every parent had both children).
For example,
Given the following perfect binary tree,
1 / 2 3 /\ / 4 5 6 7
After calling your function, the tree is should look like:
1, NULL / 2, 3, null /\ / 4->5->6->7, NULL
Wide Search + recursion
Recursion two times
The tree after CONNECTLR ()
1, NULL / 2 3, null /\ / 4->5 6->7, NULL
Connectrl () for connecting right subtree to left subtree run time: 436ms
/** * Definition for binary tree with next pointer. * public class Treelinknode {* int val; * Treelinknode left, right, next; * treelinknode (int x) {val = x;} *} */public class Solution {public void connect (Treelinknode root) {if (root = null) RETURN;CONNECTLR (root); Connectrl (ro OT);} private void Connectlr (Treelinknode root) {if (root.left==null) Return;root.left.next = ROOT.RIGHT;CONNECTLR (root.left ); CONNECTLR (root.right);} private void Connectrl (Treelinknode root) {if (root.left==null) return;if (root.next!=null) {Root.right.next = Root.next.left;} Connectrl (Root.left); Connectrl (root.right);}}
Time to complete a recursive run: 440ms
/** * Definition for binary tree with next pointer. * public class Treelinknode {* int val; * Treelinknode left, right, next; * treelinknode (int x) {val = x;} *} */public class Solution {public void connect (Treelinknode root) {connect (root,null);} private void Connect (Treelinknode root, treelinknode brother) {if (root = null) Return;root.next = Brother;connect ( Root.left,root.right); if (brother!=null) {connect (root.right,brother.left);} Else{connect (Root.right,null);}}}
[Leetcode] Populating Next right pointers in each Node