110.平衡二叉树202.左叶子之和

32 阅读1分钟

110.平衡二叉树

class Solution {
    public boolean isBalanced(TreeNode root) {
        return getHeight(root) != -1;
    }
    private int getHeight(TreeNode node){
        if(node == null) return 0;
        int left = getHeight(node.left);
        if(left == -1) return -1;
        int right = getHeight(node.right);
        if(right == -1) return -1;
        if(Math.abs(left - right) > 1) return -1;
        return Math.max(left,right) + 1;
    }
}

202.左叶子之和

image.png

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