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
Subscribe to see which companies asked this question
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 classSolution {Ten Public voidConnect (Treelinknode root) { One if(Root = =NULL)return; ATreelinknode cur =root;//use cur to traverse through layers - while(Root.left! =NULL){ -Cur =Root; the while(cur! =NULL){ -Cur.left.next =Cur.right; - if(Cur.next! =NULL) -Cur.right.next =Cur.next.left; +Cur =Cur.next; - } +Root =Root.left; A } at } -}
The use of stacks or queues can also be done. But that would be beyond the question.
- Constant extra space. The requirements.
What if it's not a complete binary tree?
Populating Next right pointers in each Node Java solutions