leetcode404_左叶子之和

题目链接:https://leetcode-cn.com/problems/sum-of-left-leaves/
要读懂题目,题目要的是左叶子之和,是左叶子不是做节点!

最开始的写法:

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

反思:但凡是树的递归,你必须要想清楚,到底是哪个序列的遍历?
这里是后序遍历(左右中),因为你需要计算出左右子树的左叶子的节点,然后和本树的左叶子相加,最后返回。

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

其实可能前序遍历和后序遍历差不多吧,比如精简版的就用的是前序遍历:

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if(root == null) return 0;
        int midValue = 0;
        if(root.left != null && root.left.left == null && root.left.right == null) midValue += root.left.val;
        return midValue + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
    }
}
posted @ 2022-03-06 09:49  明卿册  阅读(4)  评论(0编辑  收藏  举报