代码随想录算法训练营第十七天| LeetCode110 平衡二叉树 、LeetCode257 二叉树的所有路径、LeetCode404 左叶子之和

LeetCode110 平衡二叉树

题目链接:https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html代码:

public class code110 {
    public boolean isBalanced(TreeNode root) {
        if (getHeight(root) == -1) {
            return false;
        }
        return true;
    }

    private int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        if (leftHeight == -1) {
            return -1;
        }
        if (rightHeight == -1) {
            return -1;
        }
        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }
        return 1 + Math.max(leftHeight, rightHeight);
    }
}

遍历顺序依然为后序,如果左右孩子不为平衡二叉树,直接返回-1,如果当前节点的左右孩子高度差大于1,直接返回-1

LeetCode257 二叉树的所有路径

题目链接:https://programmercarl.com/0257.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%89%80%E6%9C%89%E8%B7%AF%E5%BE%84.html代码:

public class code257 {
    public List<String> binaryTreePaths(TreeNode root) {

        List<String> res = new ArrayList<>();
        getPath(root, "", res);
        return res;
    }

    private void getPath(TreeNode root, String path, List<String> res) {
        if (root == null) {
            return;
        }
        // 如果是叶子节点,将路径添加到结果集中
        if (root.left == null && root.right == null) {
            res.add(path + root.val);
            return;
        }
        // 如果不是叶子节点,遍历左右孩子
        getPath(root.left, path + root.val + "->", res);
        getPath(root.right, path + root.val + "->", res);
    }

}

遍历顺序为前序遍历

LeetCode404 左叶子之和

题目链接:https://programmercarl.com/0404.%E5%B7%A6%E5%8F%B6%E5%AD%90%E4%B9%8B%E5%92%8C.html代码:

public class code404 {
    public int sumOfLeftLeaves(TreeNode root) {

        if (root == null) return 0;
        int leftSum = sumOfLeftLeaves(root.left);   // 左
        int rightSum = sumOfLeftLeaves(root.right);   // 右

        int midValue = 0;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            midValue = root.left.val;
        }
        int sum = midValue + leftSum + rightSum;
        return sum;
    }
}

遍历顺序为后序遍历,注意左叶子的判定条件

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值