感觉理解不是很透彻

110.平衡二叉树

    /**
     * <A href="https://leetcode.cn/problems/balanced-binary-tree/">110. 平衡二叉树</A>
     * <BR>
     */
    public boolean isBalanced(TreeNode root) {
        return Math.abs(getHeight(root.left) - getHeight(root.right)) <= 1;
    }

    public int getHeight(TreeNode cur) {
        if (cur == null) return 0;
        int left = getHeight(cur.left);
        if (left == -1) {
            return -1;
        }
        int right = getHeight(cur.right);
        if (right == -1) {
            return -1;
        }
        if (Math.abs(right - left) > 1) {
            return -1;
        }
        return Math.max(left, right) + 1;
    }

257. 二叉树的所有路径

public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String>();
        List<Integer> path = new ArrayList<>();
        if (root == null) {
            return result;
        }
        getPath(root, path, result);
        return result;
    }

    public void getPath(TreeNode cur, List<Integer> path, List<String> result) {
        path.add(cur.val);
        String wayPath = "";
        if (cur.left == null && cur.right == null) {
            for (Integer integer : path) {
                wayPath += integer + "->";
            }
            wayPath = wayPath.substring(0, wayPath.length() - 2);
            result.add(wayPath);
            return;
        }
        if (cur.left != null) {
            getPath(cur.left, path, result);
            path.remove(path.size() - 1);
        }
        if (cur.right != null) {
            getPath(cur.right, path, result);
            path.remove(path.size() - 1);
        }
    }

404. 左叶子之和

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

        int mid = 0;
        int left = sumOfLeftLeaves(root.left);
        int right = sumOfLeftLeaves(root.right);
        if (root.left != null && (root.left.left == null && root.left.right == null)) {
            mid = root.left.val;
        }
        return mid + right + left;
    }
}

posted @ 2022-12-27 00:38  维萨斯  阅读(16)  评论(0)    收藏  举报