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
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
巧妙地利用一个头链表完成。
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode *ChildFrontNode = new TreeLinkNode (0);//子链表头节点
TreeLinkNode *pre = ChildFrontNode;//记录先前值,方便生成链表
while(root){
if(root->left){
pre->next = root->left;
pre = pre->next;
}
if(root->right){
pre->next = root->right;
pre = pre->next;
}//两个子节点生成链表
root = root->next; // 根节点指向下一个
if(root==NULL){
root = ChildFrontNode->next;
pre = ChildFrontNode;
ChildFrontNode->next = NULL; //走到链表尾部,转到下一行ChildFrontNode
}
}
}
};
本文介绍了一种解决二叉树中填充每个节点的Next指针的方法,即使对于任意二叉树也能有效工作,并且仅使用常数额外空间。通过构建一个虚拟头节点来连接同一层级的所有节点,实现了一种新颖而高效的解决方案。
2923

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



