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
和上一题解法完全相同!
/**
* 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) {
if(root == NULL) return;
queue<TreeLinkNode *> level;
level.push(root);
while(!level.empty()) {
queue<TreeLinkNode *> newlevel;
while(!level.empty()) {
TreeLinkNode *front = level.front();
if(front->left != NULL)
newlevel.push(front->left);
if(front->right != NULL)
newlevel.push(front->right);
level.pop();
if(!level.empty())
front->next = level.front();
}
level = newlevel;
}
}
};
本文讨论了如何在不使用额外空间的情况下,为任意给定的二叉树节点添加相邻指针,以实现节点之间的连接。通过队列结构遍历树的层次,确保每个节点正确地指向其下一个节点。
416

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



