• 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;
    }
  • 相关阅读:
    WPF线程调用UI元素
    WPF使用阿里巴巴矢量图标图ttf
    WPF读取Excel表格数据到DataGrid
    WPF开发的软件在触摸屏当操作遇到边界时
    WPF 全局样式(滚动条)
    WPF TextBox文本自动换行
    Maven : Cannot download sources
    nginx关闭后仍然能够访问localhost:80
    微信公众号开发总结
    CAT window10 本地安装
  • 原文地址:https://www.cnblogs.com/bonelee/p/8661016.html
Copyright © 2020-2023  润新知