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

103 阅读1分钟

110. 平衡二叉树

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

257. 二叉树的所有路径

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        dfs(root, "", res);
        return res;
    }
    private void dfs(TreeNode root, String path, List<String> res){
        if(root == null)return;

        path += root.val;

        if(root.left == null && root.right == null){ // 当前节点是叶节点
            res.add(path);
            return;
        }

        // 如果当前节点不是叶节点
        path += "->";
        dfs(root.left, path, res);
        dfs(root.right, path, res);
    }
}
  • 当我们将当前节点的值加到 path 并调用 dfs 为左孩子或右孩子时,我们没有真正地修改原始的 path。在 Java 中,字符串是不可变的,所以每次我们对 path 进行修改(如 path += "->"),我们实际上是创建了一个新的字符串。这意味着当我们从一个递归调用返回到上一个调用时,path 的值仍然是未修改的。
  • 当我们完成左子树的搜索并返回,path 仍然是指向当前节点的,所以我们可以无障碍地开始搜索右子树。

因此,这段代码的回溯体现在 path 字符串的修改和恢复上。每次递归调用都有其自己的 path 副本,而不会影响其他调用的 path

404. 左叶子之和

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if(root == null)return 0;

        int leftValue = sumOfLeftLeaves(root.left); // 左
        int rightValue = sumOfLeftLeaves(root.right); // 右

        int midValue = 0;
        if(root.left != null && root.left.left == null && root.left.right == null){ // 根的左子树就是左叶子
            midValue = root.left.val;
        }

        return leftValue + rightValue + midValue;
    }
}