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.
EX:
Example 1:

Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers,with '#' signifying the end of each level.想法: 因為是 perfect binary tree,所以每個 node n 的 left child 的 next 一定是指向他的 right child,
而 right child 的 next 則會指向 n 的 next 的 left child,知道這層關係之後只需要用 DFS 做 inorder traverse,然後照上述方式更新當前 node 的 next指標即可。
完整程式碼:解法一(recursive):class Solution {
public:
Node* connect(Node* root) {
if (root == nullptr) { return nullptr; }
if (root->left != nullptr) {
root->left->next = root->right;
}
if (root->right != nullptr) {
root->right->next = (root->next)? root->next->left : nullptr;
}
connect(root->left);
connect(root->right);
return root;
}
};解法二(iterative):class Solution {
public:
Node* connect(Node* root) {
if (root == nullptr) { return root; }
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
Node* cur = q.front();
q.pop();
if (cur->left != nullptr) {
cur->left->next = cur->right;
q.push(cur->left);
}
if (cur->right != nullptr) {
cur->right->next = (cur->next)? cur->next->left : nullptr;
q.push(cur->right);
}
}
}
return root;
}
};
沒有留言:
張貼留言