zoukankan      html  css  js  c++  java
  • leetcode 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.
    
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            # traverse tree, if node.left is leaf them sum it
            #if is_leaf(root) and direct is left:
            #    sum it
                    
            def sum_left_leaf(node, is_left, sums):
                if not node: return
                if node and (not node.left) and (not node.right) and is_left:
                    sums[0] += node.val
                    return
                sum_left_leaf(node.left, True, sums)
                sum_left_leaf(node.right, False, sums)
            
            sums = [0]
            sum_left_leaf(root, False, sums)
            return sums[0]                

    更简洁的写法:

    class Solution(object):
        def sumOfLeftLeaves(self, root):
            if not root:
                return 0
            if root.left and not root.left.left and not root.left.right:
                return root.left.val + self.sumOfLeftLeaves(root.right)
            return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

    迭代解法:

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            # traverse tree, if node.left is leaf them sum it
            #if is_leaf(root) and direct is left:
            #    sum it
            ans = 0
            if not root: return ans        
            stack = [(root, False)]
            while stack:
                node, is_left = stack.pop()
                if not node.left and not node.right and is_left:
                    ans += node.val
                if node.right: stack.append((node.right, False))
                if node.left: stack.append((node.left, True))
            return ans
                            

    另外也可以在迭代过程中绕过叶子结点:

    Iterative method. Here for each node in the tree we check whether its left child is a leaf. If it is true, we add its value to answer, otherwise add left child to the stack to process it later. For right child we add it to stack only if it is not a leaf.
    
    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;
    }
  • 相关阅读:
    POJ 3977 折半枚举
    [CQOI2007]余数求和 (分块+数学
    NOI P1896 互不侵犯 状压DP
    HDU 5446 Unknown Treasure (卢卡斯+CRT
    宁夏邀请赛F FLOYD
    P1414 又是毕业季II (数学?
    P2051 [AHOI2009]中国象棋 DP
    POJ 2449:Remmarguts' Date(A* + SPFA)
    HDU 6215:Brute Force Sorting(链表+队列)
    HDU 6207:Apple(Java高精度)
  • 原文地址:https://www.cnblogs.com/bonelee/p/8661016.html
Copyright © 2011-2022 走看看