leetcode第116题填充每个节点的下一个右侧指针

leetcode第116题填充每个节点的下一个右侧指针

第一种方式:

难点还是在于:如何把题目的要求细化为每个节点需要做的事情,但是如果只依赖一个节点的话,是没有办法跨父节点进行连接的.

//难点在于如何将父节点不相同的子节点进行连接  需要进行拆分
class Solution {
    public Node connect(Node root) {
        if (root == null) {
            return null;
        }

        connextNode(root.left, root.right);
        return root;
    }

    public Node connextNode(Node Node1, Node Node2) {
        if (Node1 == null || Node2 == null) {
            return null;
        }

        //这里对链表进行操作
        Node1.next = Node2;
        //连接父节点相同的子节点,
        connextNode(Node1.left, Node1.right);
        connextNode(Node2.left, Node2.right);
        //连接跨越父节点的两个子节点
        connextNode(Node1.right, Node2.left);
        return Node1;
    }
}

**第二种方式:**找规律,相邻的节点进行串联

class Solution {
    public Node connect(Node root) {
            if (root == null) {
            return null;
        }

        dfs(root);
        return root;
    }

    //深搜进行操作
    void dfs(Node root) {
        if (root == null) {
            return;
        }
        
        Node left = root.left;
        Node right = root.right;
        while (left != null) {
            left.next = right;
            left = left.right;
            right = right.left;
        }
        
        dfs(root.left);
        dfs(root.right);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值