Day15 | 二叉树part03

60 阅读1分钟

110. 平衡二叉树 - 力扣(LeetCode)

class Solution {
    private Integer depth;

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (Math.abs(height(root.left) - height(root.right)) > 1) {
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

    private int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(height(root.left), height(root.right)) + 1;
    }
}

257. 二叉树的所有路径 - 力扣(LeetCode)

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        dfs(root, new ArrayList<>(), result);
        return result;
    }

    private void dfs(TreeNode node, List<Integer> path, List<String> result) {
        path.add(node.val);
        if (node.left == null && node.right == null) {
            result.add(convertPath(path));
        } else {
            if (node.left != null) {
                dfs(node.left, path, result);
                path.remove(path.size() - 1);// 回溯
            }
            if (node.right != null) {
                dfs(node.right, path, result);
                path.remove(path.size() - 1);// 回溯
            }
        }
    }

    private String convertPath(List<Integer> list) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
            if (i < list.size() - 1) {
                sb.append("->");
            }
        }
        return sb.toString();
    }
}

404. 左叶子之和 - 力扣(LeetCode)

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

222. 完全二叉树的节点个数 - 力扣(LeetCode)

public int countNodes(TreeNode root) {
    if (root == null){
        return 0;
    }
    return countNodes(root.left) + countNodes(root.right) + 1;
}