404. Sum of Left Leaves

题目描述

404. Sum of Left Leaves

方法思路

很简单的题目可以递归,也可以迭代

Approach1:iterative

class Solution {
    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;
                stack.push(node.left);
            }
            if(node.right != null) {
                stack.push(node.right);
            }
        }
    return ans;
}
}

Approach2:recursive + Global variable

class Solution {
    //Runtime: 3 ms, faster than 100.00%
    //Memory Usage: 40.9 MB, less than 5.30%
    int sum = 0;
    public int sumOfLeftLeaves(TreeNode root) {
        if(root == null) return 0;
        if(root.left != null && root.left.left == null && root.left.right == null){
            sum += root.left.val;
        }
        sumOfLeftLeaves(root.left);
        sumOfLeftLeaves(root.right);
        return sum;
    }
}

Approach:recursive

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;
        else ans += sumOfLeftLeaves(root.left);
    }
    ans += sumOfLeftLeaves(root.right);
    
    return ans;
}
}