117. Populating Next Right Pointers in Each Node II 计算右边的附属节点

[抄题]:

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.
  • Recursive approach is fine, implicit stack space does not count as extra space for this problem.

Example:

Given the following binary tree,

     1
   /  \
  2    3
 / \    \
4   5    7

After calling your function, the tree should look like:

     1 -> NULL
   /  \
  2 -> 3 -> NULL
 / \    \
4-> 5 -> 7 -> NULL

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道递归的关系:递归recursion分成遍历traverse一个人走,dc分治法两个人走

[一句话思路]:

利用不写公式的递归,先单层遍历,再多层遍历

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 已经声明过,就开辟过空间,不需要再次声明。但是可以赋值
  2. 同一层每个节点都要算,所以curr = curr.next;

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

不用q的层遍历,算个特例吧

[复杂度]:Time complexity: O(1 并没有新建一棵树) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

不用q的遍历

[算法思想:递归/分治/贪心]:递归

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void connect(TreeLinkNode root) {
        //ini: curr, head, prev
        TreeLinkNode head = root;
        TreeLinkNode curr = null;
        TreeLinkNode prev = null;
        
        while (head != null) {
            //ini
            curr = head;
            head = null;
            prev = null;
            
            while (curr != null) {
                if (curr.left != null) {
                    if (prev != null) 
                        //join up
                        prev.next = curr.left;
                    else head = curr.left;
                    //update prev
                    prev = curr.left;
                }
                
                if (curr.right != null) {
                    if (prev != null) 
                        //join up
                        prev.next = curr.right;
                    else head = curr.right;
                    //update prev
                    prev = curr.right;
                }
                //in the same level
                 curr = curr.next;
            }
           
    }
    }
}
View Code

 

转载于:https://www.cnblogs.com/immiao0319/p/9020662.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值