/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void findNext(TreeLinkNode *node, TreeLinkNode *target) {
while (node) {
if (node->left) {
target->next = node->left;
break;
} else if (node->right) {
target->next = node->right;
break;
} else {
node = node->next;
}
}
}
void connect(TreeLinkNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root) return;
if (root->right) {
findNext(root->next, root->right);
}
if (root->left) {
if (root->right) {
root->left->next = root->right;
} else {
findNext(root->next, root->left);
}
}
connect(root->right);
connect(root->left);
}
};
Small Case: 8ms
Large Case: 212ms
Time: O(n)
Space: O(1)
1. 由于只能使用常数空间,因此无法使用BFS
2. 注意先访问右子树再访问左子树,从右往左构建next指针