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

110. 平衡二叉树

leetcode
文档题解
视频题解

从平衡二叉树的高度差入手,本质还是求子树的高度。

class Solution {
    public boolean isBalanced(TreeNode root) {
        return getHeight(root) != -1;
    }

    // 返回高度为 -1,说明不是平衡二叉树
    public int getHeight(TreeNode node) {
        if (node == null) return 0;

        int lh = getHeight(node.left);
        if (lh == -1) return -1;
        int rh = getHeight(node.right);
        if (rh == -1) return -1;

        // 左右子树的高度差大于 1,不是平衡二叉树
        if (Math.abs(lh - rh) > 1) return -1;

        return Math.max(lh, rh) + 1;
    }
}

257. 二叉树的所有路径

leetcode
文档题解
视频题解

本题用到了回溯的技巧,本质上还是递归,在处理完左子树后,还原信息,继续处理右子树。

// 前序遍历
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new LinkedList<>();
        helper(root, "", res);
        return res;
    }

    public void helper(TreeNode node, String path, List<String> res) {
        path += node.val;
        // 叶子节点,一个解
        if (node.left == null && node.right == null) {
            res.add(path);
            return;
        }
        if (node.left != null) {
            // 这里并没有修改 path 的值,但也是在回溯
            // 即进入 helper 之时让 path 更进一步
            // 在退出 helper 之后让 path 回退一步
            // 这里传入的是 path + "->",并没有修改 path
            // 退出后也不需要回退 path
            helper(node.left, path + "->", res);
        }
        if (node.right != null) {
            helper(node.right, path + "->", res);
        }
    }
}

404. 左叶子之和

leetcode
文档题解
视频题解

后序遍历,左右子树的左叶子之和就是以当前节点为根的树的左叶子之和。

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        // 其实这个也可以不写,不写不影响结果,但就会让递归多进行了一层。
        if (root.left == null && root.right == null) return 0;

        int lh = sumOfLeftLeaves(root.left);
        int rh = sumOfLeftLeaves(root.right);

        // 回到 root,判断是否有左叶子
        if (root.left != null && root.left.left == null && root.left.right == null) {
            lh = root.left.val;
        }

        return lh + rh;
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注