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