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.
与116不同的是本题不是完全二叉树,而是一棵普通二叉树,即并非每个节点都有左右节点且左右节点高度一致。
找到root节点的next即可。
class Solution {
public:
Node* connect(Node* root) {
if(!root) return root;
Node* cur = root->next;
while(cur){
if(cur->left){
cur = cur->left;
break;
}
if(cur->right){
cur=cur->right;
break;
}
cur = cur->next;
}
if(root->right){
root->right->next = cur;
cur = root->right;
}
if(root->left){
root->left->next = cur;
}
connect(root->right);
connect(root->left);
return root;
}
};