leetcode 116. Populating Next Right Pointers in Each Node 最简单栈解法

下一题117. Populating Next Right Pointers in Each Node II

题意

输入:一个完美二叉树

输出:改变二叉树使所有节点的next指向右边的节点

思路:

stack存右边的每一个深度的最左节点,最深的在栈底。代码比较简洁,直接看代码吧。

解:

    // Runtime: 1 ms, faster than 55.64% of Java online submissions for Populating Next Right Pointers in Each Node.
    //Memory Usage: 38.9 MB, less than 15.35% of Java online submissions for Populating Next Right Pointers in Each
    private final Stack<Node> stack = new Stack<>();
    public Node connect(Node root) {
        if (root == null)
            return null;

        root.next = stack.isEmpty() ? null : stack.pop();
        connect(root.right);
        connect(root.left);
        stack.push(root);
        return root;
    }
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页