Populating Next Right Pointers in Each Node - LeetCode
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *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
.
Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
思路:通过递归,从root节点向下进行DFS。当遍历到一个节点时,如果它有孩子节点,则将左孩子的next指针指向右孩子。
重点是右孩子的next指针该如何处理。在这里,我们每次递归时都向下传递一个指针,即当前节点的next指针。
当我们要处理当前节点的右孩子next指针时,实际上它应该指向当前节点next指针所指向的节点的左孩子。
此外,在递归时还要判断下,二叉树最右侧的节点的next指针都要为NULL。
1 class Solution { 2 public: 3 void dfs(TreeLinkNode *root, TreeLinkNode *parent_next) 4 { 5 if (root->left == NULL) return; 6 root->left->next = root->right; 7 root->right->next = (parent_next) ? 8 parent_next->left : NULL; 9 dfs(root->left, root->left->next); 10 dfs(root->right, root->right->next); 11 } 12 void connect(TreeLinkNode *root) { 13 if (root == NULL) return; 14 dfs(root, NULL); 15 } 16 };