刷题日记15 | 110.平衡二叉树、257. 二叉树的所有路径、404.左叶子之和

62 阅读1分钟

刷题日记15

今天依然是二叉树,要注意求二叉树的深度和高度是不同的。

二叉树的深度是从根节点到叶子节点的最大路径边的条数

二叉树的高度指的是从某个节点到叶子节点的最长路径边的条数

image.png

110. 平衡二叉树

后序遍历,后序遍历是求高度的方法

class Solution {
    public boolean isBalanced(TreeNode root) {
        int res = getHeight(root);
        return res == -1 ? false : true;
    }
    public int getHeight(TreeNode root){
        if(root == null) return 0;
        int leftDepth = getHeight(root.left); // 左
        if(leftDepth == -1) return -1;
        int rightDepth = getHeight(root.right); // 右
        if(rightDepth == -1) return -1;
        int res = 1;
        res = Math.abs(leftDepth - rightDepth) > 1 ? -1 : Math.max(leftDepth, rightDepth) + 1; // 中
        return res;
    }
}

257. 二叉树的所有路径

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new LinkedList<>();
        LinkedList<Integer> path = new LinkedList<>();
        if(root == null) return res;
        getPath(root, path, res);
        return res;
    }
    public void getPath(TreeNode root, LinkedList<Integer> path, List<String> res){
        path.offer(root.val);
        if(root.left == null && root.right == null){
            StringBuilder sb = new StringBuilder();
            for(Integer i : path){
                sb.append(i.toString());
                sb.append("->");
            }
            sb.delete(sb.length()-2, sb.length());
            res.add(sb.toString());
            return;
        }
        if(root.left != null){
            getPath(root.left, path, res);
            path.pollLast();
        }
        if(root.right != null){
            getPath(root.right, path, res);
            path.pollLast();
        }
    }
}

404. 左叶子之和

左叶子就是叶子结点,如果不是叶子节点则不算。使用递归法,后序遍历,在返回值上累加即可。

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