[LeetCode] Populating Next Right Pointers in Each Node II

简介: The problem becomes more difficult once the binary tree is not perfect. The idea is still similar to use a level-order traversal.

The problem becomes more difficult once the binary tree is not perfect. The idea is still similar to use a level-order traversal. Note that we do not need to maintain a queue for the traversal becase the next pointer has provided us with the required information.

The following code is taken from the last answer of this link, which is concise and clean. The use of a dummy node simplifies the code. You may play with the code on some examples to see how it works.

 1 class Solution {
 2 public:
 3     void connect(TreeLinkNode *root) {
 4         TreeLinkNode* dummy = new TreeLinkNode(0);
 5         dummy -> next = root;
 6         while (dummy -> next) {
 7             TreeLinkNode* pre = dummy;
 8             TreeLinkNode* cur = dummy -> next;
 9             pre -> next = NULL;
10             while (cur) {
11                 if (cur -> left) {
12                     pre -> next = cur -> left;
13                     pre = pre -> next;
14                 }
15                 if (cur -> right) {
16                     pre -> next = cur -> right;
17                     pre = pre -> next;
18                 }
19                 cur = cur -> next;
20             }
21         }
22     }
23 };

 

目录
相关文章
|
5月前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
41 0
LeetCode 116. Populating Next Right Pointers
给定一颗二叉树,填充每一个节点的next指针使其指向右侧节点。 如果没有下一个右侧节点,则下一个指针应设置为NULL。
79 0
LeetCode 116. Populating Next Right Pointers
|
数据库
LeetCode(数据库)- 2142. The Number of Passengers in Each Bus I
LeetCode(数据库)- 2142. The Number of Passengers in Each Bus I
195 0
|
数据库
LeetCode(数据库)- The Category of Each Member in the Store
LeetCode(数据库)- The Category of Each Member in the Store
113 0
LeetCode之Next Greater Element I
LeetCode之Next Greater Element I
78 0