力扣404题(左叶子之和)

404、左叶子之和

基本思想:

首先要注意是判断左叶子,不是二叉树左侧节点,所以不能用层序遍历。

左叶子的定义:如果左节点不为空,且左节点没有左右孩子,那么这个节点就是左叶子

具体实现:

1、递归参数和返回值

参数:根节点

返回值:数值之和

2、终止条件

root==null

3、单层递归的逻辑

遇到左叶子节点的时候,记录数值

通过递归求左子树左叶子之和

右子树左叶子之和

相加就是整个树的左叶子之和

代码:

只能后序

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

 

 

迭代 前中后序都能实现

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        Stack<TreeNode> stack = new Stack<> ();
        stack.add(root);
        int result = 0;
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            if (node.left != null && node.left.left == null && node.left.right == null) {
                result += node.left.val;
            }
            if (node.right != null) stack.add(node.right);
            if (node.left != null) stack.add(node.left);
        }
        
        return result;
    }
}

 

posted @ 2021-11-10 22:44  最近饭吃的很多  阅读(31)  评论(0)    收藏  举报