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

61 阅读2分钟

110.平衡二叉树

题目链接:110. 平衡二叉树

思路:其实是判断左右子树的高度差是否大于1。判断高度的话仍然是采用后序遍历。

class Solution {
    private boolean flag = true;
    public boolean isBalanced(TreeNode root) { // 左右子树高度差不超过1
        getHeight(root);
        return this.flag;
    }
    public int getHeight(TreeNode node) {
        if (node == null) return 0;
        int left = getHeight(node.left);
        int right = getHeight(node.right);
        if (Math.abs(left - right) > 1) { // 不符合条件的时候修改标记。
            this.flag = false;
        }
        return Math.max(left, right) + 1;
    }
}

随想录中的后序递归方法没有使用全局的标记,而是不符合条件的时候向上层返回-1,然后通过最后返回到根节点的是否是-1来判断。

257.二叉树的所有路径

题目链接:257. 二叉树的所有路径

思路:只能采用前序遍历,同时这里要进行回溯的过程。(其实递归都用到了回溯,这里更明显。)通过回溯将已经存入结果的路径节点取出。

class Solution {
    public List<String> binaryTreePaths(TreeNode root) { // 前序遍历
        List<Integer> path = new ArrayList<>();
        List<String> ans = new ArrayList<>();
        traversal(root, path, ans);
        return ans;
    }
    public void traversal(TreeNode node, List<Integer> path, List<String> ans) {
        path.add(node.val); 
        if (node.left == null && node.right == null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < path.size(); i++) {
                sb.append(String.valueOf(path.get(i)));
                if (i < path.size() - 1) {
                    sb.append("->");
                }
            }
            ans.add(sb.toString());
            return;
        }
        if (node.left != null) {
            traversal(node.left, path, ans);
            path.remove(path.size() - 1); // 回溯
        }
        if (node.right != null) {
            traversal(node.right, path, ans);
            path.remove(path.size() - 1); // 回溯
        }
    }
}

404.左叶子之和

题目链接:404. 左叶子之和

思路:我采用了前序遍历,注意判断是否是左叶子时,要在他的父节点那里进行判断。因为到了叶子节点就无法判断出是否是左叶子节点了。随想录采用后序遍历,后序的思路更加清晰,直接将符合条件的节点值返回到上层就好,不需要定义全局变量。

class Solution {
    private int count = 0;
    public int sumOfLeftLeaves(TreeNode root) { // 前序遍历。
        if (root == null) return 0;
        getCount(root);
        return this.count;
    }
    public void getCount(TreeNode node) {
        if (node.left == null && node.right == null) return;
        if (node.left != null && node.left.left == null && node.left.right == null) {
            this.count += node.left.val;
        }
        if (node.left != null) {
            getCount(node.left);
        }
        if (node.right != null) {
            getCount(node.right);
        }
    }
}

注意:以上的题目也都可以用迭代法来做,过两天在本文中更新迭代法。