You are given a perfect binary treewhere 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.
给定一个完全二叉树,层序遍历,找到每个节点的下一个右向指针。
若root及其子节点存在,则root->left->next为root->right,root->right->next为root->next的左子节点。
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() {}
Node(int _val, Node* _left, Node* _right, Node* _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public:
Node* connect(Node* root) {
if(!root) return root;
if(root->left) {
root->left->next = root->right;
if(root->next){
root->right->next = root->next->left;
}else{
root->right->next == NULL;
}
}
connect(root->left);
connect(root->right);
return root;
}
};