Given a binary treenode
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.spa
Initially, all next pointers are set to NULL
.code
Note:blog
For example,
Given the following perfect binary tree,遞歸
1 / \ 2 3 / \ / \ 4 5 6 7
After calling your function, the tree should look like:it
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
這個題想法仍是比較單純簡單的,由於是徹底二叉樹,因此先將二叉樹總體最右邊一列的next賦值爲NULL,而後考慮根節點兩棵子樹之間的關係,遞歸。
代碼:
1 void right_null(TreeLinkNode* root) 2 { 3 root->next=NULL; 4 if (root->right==NULL) 5 return; 6 right_null(root->right); 7 } 8 9 void mid_next(TreeLinkNode* lefts,TreeLinkNode* rights) 10 { 11 lefts->next=rights; 12 TreeLinkNode* le=lefts; 13 TreeLinkNode* ri=rights; 14 while(le->right!=NULL) 15 { 16 le->right->next=ri->left; 17 le=le->right; 18 ri=ri->left; 19 } 20 if (lefts->left==NULL) 21 return; 22 mid_next(lefts->left,lefts->right); 23 mid_next(rights->left,rights->right); 24 } 25 26 void connect(TreeLinkNode *root) 27 { 28 if(root==NULL) 29 return; 30 right_null(root); 31 if (root->left==NULL) 32 return; 33 mid_next(root->left,root->right); 34 35 }