Given a binary tree
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
.
Initially, all next pointers are set to NULL
.
Note:
For example,
Given the following perfect binary tree,
1 / 2 3 / \ / 4 5 6 7
After calling your function, the tree should look like:
1 -> NULL / 2 -> 3 -> NULL / \ / 4->5->6->7 -> NULL
这题首先想到的当然是用bfs来做,但是题目只允许使用常数量的额外空间,用queue肯定是无法实现的,那么可以采取先序遍历的方式,由于是完全二叉树,所以有左孩子那么就一定也有右孩子了,所以递归的时候注意这点就可以了。下面是代码:
1 class Solution { 2 public: 3 void connect(TreeLinkNode *root) { 4 preorderTranversal(root); 5 } 6 7 void preorderTranversal(TreeLinkNode *root) 8 { 9 if(!root || !root->left) return; 10 root->left->next = root->right; 11 if(root->next) 12 root->right->next = root->next->left;//这一步的连接应该注意一下 13 preorderTranversal(root->left); 14 preorderTranversal(root->right); 15 } 16 };
LeetCode OJ:Populating Next Right Pointers in Each Node(指出每一个节点的下一个右侧节点)
原文:http://www.cnblogs.com/-wang-cheng/p/4914246.html