​LeetCode刷题实战545:二叉树的边界

2022-04-12 18:54:50 浏览数 (1)

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试 算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做二叉树的边界,我们先来看题面:

https://leetcode-cn.com/problems/boundary-of-binary-tree/

Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate nodes.

Left boundary is defined as the path from root to the left-most node. Right boundary is defined as the path from root to the right-most node. If the root doesn't have left subtree or right subtree, then the root itself is left boundary or right boundary. Note this definition only applies to the input binary tree, and not applies to any subtrees.

The left-most node is defined as a leaf node you could reach when you always firstly travel to the left subtree if exists. If not, travel to the right subtree. Repeat until you reach a leaf node.

The right-most node is also defined by the same way with left and right exchanged.

给定一棵二叉树,以逆时针顺序从根开始返回其边界。边界按顺序包括左边界、叶子结点和右边界而不包括重复的结点。(结点的值可能重复)

左边界的定义是从根到最左侧结点的路径。右边界的定义是从根到最右侧结点的路径。若根没有左子树或右子树,则根自身就是左边界或右边界。注意该定义只对输入的二叉树有效,而对子树无效。

最左侧结点的定义是:在左子树存在时总是优先访问,如果不存在左子树则访问右子树。重复以上操作,首先抵达的结点就是最左侧结点。

最右侧结点的定义方式相同,只是将左替换成右。

示例

解题

https://www.cnblogs.com/kpwong/p/14717680.html

解题思路:

根据观察,我们发现

当node为leftBound左边界时,node.left也是左边界

当node为leftBound左边界时,node.left为空,则node.right也可以leftBound左边界。

Bottom的所有都要加入其中。

rightBound也是如此。

我们可以循环调用dfs,初始化leftBound和rightBound两个boolean参数,一层层判断。先加入左边,加入bottom,然后得到两个子树加入,最后加入右边界。

代码如下:

代码语言:javascript复制
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        res.add(root.val);
        getBounds(root.left, res, true, false);
        getBounds(root.right, res, false, true);
        return res;
    }
    public void getBounds(TreeNode node, List<Integer> res, boolean leftBound, boolean rightBound) {
        if (node == null) return;
        if (leftBound) {
            res.add(node.val);
        }
        //add bottom
        if(!leftBound && !rightBound && node.left == null && node.right == null) {
            res.add(node.val);
        }
        getBounds(node.left, res, leftBound, rightBound && node.right == null);
        getBounds(node.right, res, leftBound && node.left == null, rightBound);
        if (rightBound) {
            res.add(node.val);
        }
        
        
    }

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-540题汇总,希望对你有点帮助!

LeetCode刷题实战541:反转字符串 II

LeetCode刷题实战542:01 矩阵

LeetCode刷题实战543:二叉树的直径

LeetCode刷题实战544: 输出比赛匹配对

0 人点赞