Title Description
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
The solution is to connect the nodes in the same layer, and the last next is empty. We can make use of the next feature of the tree to set the next feature of a layer, and then just go to the next row from the next layer of the left node, you can set the next layer of the next feature is OK. The code is as follows:
/** * Definition for binary tree with next pointer. * struct Treelinknode {* int val; * Treelinknode *left, *right, *next; * treelinknode (int x): Val (x), left (N ULL), right (null), Next (null) {} *}; */class Solution {public: void Connect (Treelinknode *root) { if (root==null) return; root->next=null; while (root) { Treelinknode *node=root; while (Node&&node->left) { node->left->next=node->right; Node->right->next=node->next==null? null:node->next->left; node=node->next;//point to the next node of this layer } root=root->left;//to the first node below}}} ;
Leetcode-populating Next Right pointers in each Node