[LeetCode] Populating Next Right Pointers in Each Node

简介: The idea is similar to a level-order traversal and remember to take full advantages of the prefect binary tree assumption in the problem statement.

The idea is similar to a level-order traversal and remember to take full advantages of the prefect binary tree assumption in the problem statement.

The code (iterative solution) is as follows.

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

This problem can also be solved recursively.

 1 class Solution {
 2 public:
 3     void connect(TreeLinkNode *root) {
 4         if (!root) return;
 5         if (root -> left) {
 6             root -> left -> next = root -> right;
 7             if (root -> next)
 8                 root -> right -> next = root -> next -> left;
 9         }
10         connect(root -> left);
11         connect(root -> right);
12     }
13 };

 

目录
相关文章
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
339 0
LeetCode - 19. Remove Nth Node From End of List
19. Remove Nth Node From End of List  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个链表,删除倒数第n个结点.
1106 48
LeetCode 116. Populating Next Right Pointers
给定一颗二叉树,填充每一个节点的next指针使其指向右侧节点。 如果没有下一个右侧节点,则下一个指针应设置为NULL。
221 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
394 0
|
数据库
LeetCode(数据库)- The Category of Each Member in the Store
LeetCode(数据库)- The Category of Each Member in the Store
251 0
LeetCode之Next Greater Element I
LeetCode之Next Greater Element I
269 0

热门文章

最新文章