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
Analysis: This problem is level-order traversal deformation, and level-order traversal different is that the problem requires constant space. General Level-order traversal with a container to save the previous layer of the node is O (n) space complexity, so here are different direct copy. To analyze this problem, a node P's left child's next is node P's right child, p's node right child's next is P's next node left child, by this we can only maintain node p to complete populate. The time complexity is O (n) and the spatial complexity is O (1). The code is as follows:
classSolution { Public: voidConnect (Treelinknode *root) { if(Root = NULL)return; Treelinknode*head = root;//Point-to- head of every level while(Head->left && head->Right ) {Treelinknode*cur = head;//iterate through each node at a level while(cur) {cur->left->next = cur->Right ; Cur->right->next = cur->next?cur->next->Left:null; Cur= cur->Next; } head= head->left;//update head to left child of previous head } }};
Leetcode:populating Next Right pointers in each Node