Hard-题目6:117. Populating Next Right Pointers in Each Node II

题目原文:
Follow up for problem “Populating Next Right Pointers in Each Node”.

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space.
For 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

题目大意:
给一个普通二叉树添加next节点。
题目分析:
Middle-题目17类似,区别是这里面的二叉树是普通二叉树,上一题则是完全二叉树。所以左孩子的next不一定是右孩子,右孩子的next也不一定是父节点next的左孩子,而是从父节点开始,一直向右找到一个有孩子的同层节点,然后指向其孩子(如果有左孩子就是左孩子,没有就是右孩子)。
所以每排完一层之后向下深搜的时候,要先搜右子树,再搜左子树,故本题要用逆前序遍历!!!,如果是常规的前序遍历,向左子树深搜的时候由于右子树没处理,会有一些next没连上。
源码:(language:java)

public class Solution {
    public void connect(TreeLinkNode root) {
        if(root!=null) 
            dfs(root,root.left,root.right);

    }
    private void dfs(TreeLinkNode parent, TreeLinkNode leftchild, TreeLinkNode rightchild) { // asserted that parent isn't null
        TreeLinkNode p = parent;
        while (p.next!=null && (p==parent || (p.left==null&&p.right==null)))
            p=p.next;
        if(leftchild!=null) {
            if(rightchild!=null)
                leftchild.next = rightchild;
            else {
                if(p!=parent)
                    leftchild.next = p.left!=null?p.left:p.right;
            }

        }
        if(rightchild!=null) {
            if(p!=parent)
                rightchild.next = p.left!=null?p.left:p.right;

        }
        if(rightchild!=null)
            dfs(rightchild, rightchild.left, rightchild.right);
        if(leftchild!=null)
            dfs(leftchild, leftchild.left, leftchild.right);

    }       
}

成绩:
2ms,beats 32.02%,众数2ms,39.09%
Cmershen的碎碎念:
Follow up有说到,要常数的空间复杂度,不知道递归是不是不合要求的?如果不合要求,那么可以通过改造前序遍历来实现,貌似会很麻烦……

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值