Given a binary tree
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.
递归,相较于前面的例子,多了一个while循环的判断 。
class Solution {
public:
Node* connect(Node* root) {
if (!root) return NULL;
Node *p = root->next;
while (p) {
if (p->left) {
p = p->left;
break;
}
if (p->right) {
p = p->right;
break;
}
p = p->next;
}
if (root->right) root->right->next = p;
if (root->left) root->left->next = root->right ? root->right : p;
connect(root->right);
connect(root->left);
return root;
}
};
参考博客:https://www.cnblogs.com/grandyang/p/4290148.html
博客围绕二叉树展开,要将每个节点的 next 指针指向其右侧节点,若无则设为特定值,初始时所有 next 指针都为特定值。采用递归解法,相较于之前例子多了一个 while 循环判断,还给出参考博客链接。
775

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



