Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
class Solution {
public:
void connect(TreeLinkNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!root)
return;
TreeLinkNode** array=new TreeLinkNode*[10000];
array[0]=root;
int p,q,flag;
for(p=0,q=1,flag=1 ; p!=q ; p++ ){
if(p==flag){
for(int i=p ; i<q-1 ; i++){
array[i]->next=array[i+1];
}
flag=q;
}
if(array[p]->left)
array[q++]=array[p]->left;
if(array[p]->right)
array[q++]=array[p]->right;
}
}
};
本文讨论了如何在不使用额外空间的情况下,解决任意二叉树中节点的链接问题,通过遍历二叉树并调整节点的next指针实现每一层节点的链接。
2923

被折叠的 条评论
为什么被折叠?



