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:
- 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).
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *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
.
下面说一下几种解法:
这道题目考察的是二叉树的层序遍历。类似于剑指offer中,按顺序从上往下打印二叉树结点的值。
在这里,既然考察的是遍历,那么就有递归和非递归的写法。下面先来
看递归的解法,由于是完全二叉树,所以若节点的左子结点存在的话,其右子节点必定存在,所以左子结点的next指针可以直接指向其右子节点,对于其右子节点的处理方法是,判断其父节点的next是否为空,若不为空,则指向其next指针指向的节点的左子结点,若为空则指向NULL,代码如下:
1 非递归
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return;
queue<TreeLinkNode*> q;
q.push(root);
while (!q.empty()) {
int len = q.size();
for (int i = 0; i < len; ++i) {
TreeLinkNode *t = q.front(); q.pop();
if (i < len - 1) t->next = q.front();
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
}
}
};
2 递归
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return NULL;
if (root->left) root->left->next = root->right;
if (root->right) root->right->next = root->next? root->next->left : NULL;
connect(root->left);
connect(root->right);
}
};