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

63 阅读1分钟

今日内容: 

●  110.平衡二叉树 

●  257. 二叉树的所有路径 

●  404.左叶子之和

110. 平衡二叉树

class Solution {
    public boolean isBalanced(TreeNode root) {
    //-1 表示已经不是平衡二叉树了,否则返回值是以该节点为根节点树的高度
        return getHeight(root) == -1?false:true;
    }
    private int getHeight(TreeNode root) {
        if(root == null)return 0;
        int lHeight = getHeight(root.left);
        if(lHeight == -1)return -1;
        int rHeight = getHeight(root.right);
        if(rHeight == -1)return -1;
        return Math.abs(lHeight - rHeight) > 1?-1:1+Math.max(lHeight, rHeight);
    }
}

257. 二叉树的所有路径

回溯法

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        dfs(root, "", res);
        return res;
    }
    private void dfs(TreeNode root, String path, List<String> res) {
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            res.add(path + root.val);
            return;
        }
        if(root.left != null) {
            dfs(root.left, path + root.val + "->", res);
        }
        if(root.right != null) {
            dfs(root.right, path + root.val + "->", res);
        }
    }
}

404. 左叶子之和

前序遍历

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        return dfs(root);
    }
    private int dfs(TreeNode root) {
        if(root == null)return 0;
        if(root.left == null && root.right == null)return 0;
        int sum = 0;
        if(root.left != null && root.left.left == null && root.left.right == null) {
            sum += root.left.val;
        }
        sum += dfs(root.left) + dfs(root.right);
        return sum;
    }
}