404. Sum of Left Leaves

Find the sum of all left leaves in a given binary tree.
Example

   3
   / 
  9  20
    /  
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

求二叉树左边叶子的和

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

这类题目无非就是对二叉树的遍历上面做文章,最简单的方法就是递归求解,牢记遍历时候的套路。下面是使用非递归方式,借用stack

public int sumOfLeftLeaves(TreeNode root) {
        if(root == null) return 0;
        int ans = 0;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
    
        while(!stack.empty()) {
            TreeNode node = stack.pop();
            if(node.left != null) {
                if (node.left.left == null && node.left.right == null)
                ans += node.left.val;
                else
                    stack.push(node.left);
            }
            if(node.right != null) {
                if (node.right.left != null || node.right.right != null)
                    stack.push(node.right);
            }
        }
    return ans;
}
原文地址:https://www.cnblogs.com/wxshi/p/7649054.html