1. perfect binary tree
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 toNULL
.
Initially, all next pointers are set to NULL
.
Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
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
这题想了很久还是不对,参考了http://fisherlei.blogspot.com/2012/12/leetcode-populating-next-right-pointers.html 的答案,发现原来一直忘记用next指针指向父节点的兄弟节点的子节点了,这是死脑筋!
class Solution {
public:
void connect(TreeLinkNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root==NULL)
{
return;
}
if(root->left != NULL)
root->left->next=root->right;
if(root->right!=NULL)
root->right->next=(root->next==NULL) ? NULL: root->next->left;
connect(root->left);
connect(root->right);
return;
}
};
2. 同样的题目,但是可能是imperfect binary tree, 每个节点可以有两个,一个或者没有子节点
与上题类似,必须找到有效后继结点。递归时先右子树再左子树
class Solution {
public:
void connect(TreeLinkNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root==NULL) return;
//find the first non-null child of some next pointer of root
TreeLinkNode *tmp=root->next;
TreeLinkNode *childnext=NULL;
while(tmp!=NULL)
{
if(tmp->left!=NULL)
{
childnext=tmp->left;
break;
}
else if(tmp->right!=NULL)
{
childnext=tmp->right;
break;
}
tmp=tmp->next;
}
if(root->left != NULL)
{
if(root->right!=NULL) //has both left and right child
{
root->left->next=root->right;
root->right->next=childnext;
}
else{ //has only left child
root->left->next=childnext;
}
}
else{ //has no left child
if(root->right!=NULL)
{
root->right->next=childnext;
}
}
connect(root->right);
connect(root->left);
return;
}
};