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
It's hard to think of the easy, unexpected.
/** Definition for binary tree with next pointer. * struct TREELINKNODE {* int val; * Treelinknode *left, *right, * Next * Treelinknode (int x): Val (x), left (null), Right (null), Next (null) {}}; */classSolution { Public: voidConnect (Treelinknode *root) { if(root) {if(root->Left ) Root->left->next = root->Right ; if(root->Right ) Root->right->next = Root->next? Root->next->Left:null; Connect (Root-Left ); Connect (Root-Right ); } }};
You can directly use the results from the previous layer to DFS.
Reference: http://blog.csdn.net/pickless/article/details/12027997
Populating Next right pointers in each Node (DFS, not expected)