LeetCode 116. 填充每个节点的下一个右侧节点指针

题目连接

116. 填充每个节点的下一个右侧节点指针

题目思路

这个题要求我们以常数级别的空间完成对树中next指针的连接。这个题最容易的思路就是使用中序遍历,在遍历过程中把指针连接上。但是这个题不可以使用额外的空间。
于是我们可以想到另外一个方法,我们在当前层次把下一层次的next指针安排上,因为这个树是一颗二叉树,所以next指针其实依赖于其父节点的右孩子。那么我们在当前层次就可以很顺利的把孩子指针搞定。

代码实现

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

class Solution {
    public Node connect(Node root) {
        if(root == null || (root.left == null && root.right == null)){
            return root;
        }
        helper(root);
        connect(root.right);
        connect(root.left);
        return root;
    }

    public void helper(Node root){
        if(root == null){
            return;
        }
        if(root.left != null && root.right != null){
            root.left.next = root.right;
            root.right.next = findNext(root);
        }else if(root.left == null && root.right != null){
            root.right.next = findNext(root);
        }else if(root.right == null && root.left != null){
            root.left.next = findNext(root);
        }
    }

    public Node findNext(Node root){
        root = root.next;
        return root == null? null : root.left == null? root.right : root.left;
    }
}

总结

这个题使我想多了,还以为是多叉树的连接,如果是多叉树的话就需要在findNext这个方法内进行链表的遍历,我记得lc上也有多叉树的next指针连接的题目~
通过截图

posted @ 2020-10-15 09:05  ZJPang  阅读(96)  评论(0编辑  收藏  举报