[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 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 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4638996.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值