*LeetCode-Populating Next Right Pointers in Each Node

本文介绍了一种解决树形结构中特定节点连接问题的算法。通过两种方法实现:一种是非递归方式,使用while循环逐层遍历树的节点,并调整每个节点的next指针;另一种是递归方式,直接调整当前节点的左右子节点的next指针。

这个题很巧妙

要一层一层的做 每一层记录一下第一个node 用来进入下一层 然后一个指针在这一层中向后 每次添加的是指针所在层的下一层的next

像那种right child 它的next指向parent.next.left


public class Solution {
    public void connect(TreeLinkNode root) {
        if ( root == null )
            return;
        TreeLinkNode pre = root;
        TreeLinkNode cur = root;
        while( pre.left != null ){
            cur = pre;
            while ( cur != null ){
                cur.left.next = cur.right;
                if ( cur.next != null )
                    cur.right.next = cur.next.left;
                cur = cur.next;
            }
            pre = pre.left;
        }
    }
}
recursice

public class Solution {
    public void connect(TreeLinkNode root) {
        if ( root == null )
            return;
        if ( root.left != null ){
            root.left.next = root.right;
            if ( root.next != null) 
                root.right.next = root.next.left;
        }
        connect ( root.left);
        connect ( root.right);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值