zoukankan      html  css  js  c++  java
  • 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.

    M1: recursive

    time: O(n), space: O(height)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if(root == null) {
                return 0;
            }
            int sum = 0;
            if(root.left != null && root.left.left == null && root.left.right == null) {
                sum += root.left.val;
            }
            sum += sumOfLeftLeaves(root.left);
            sum += sumOfLeftLeaves(root.right);
            return sum;
        }
    }

    M2: iterative

    对于每一个节点,检查它的left child是不是leaf,如果是就加到sum中,如果不是就把left child加入stack。

    对于每一个节点的right child,如果它不是leaf就加入stack中

    time: O(n), space: O(N)  -- 最多一层节点的个数

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            Stack<TreeNode> stack = new Stack<>();
            if(root == null) {
                return 0;
            }
            int sum = 0;
            
            stack.push(root);
            while(!stack.isEmpty()) {
                TreeNode tmp = stack.pop();
                if(tmp.left != null) {
                    if(tmp.left.left == null && tmp.left.right == null) {
                        sum += tmp.left.val;
                    } else {
                        stack.push(tmp.left);
                    }
                }
                if(tmp.right != null) {
                    if(tmp.right.left != null || tmp.right.right != null) {
                        stack.push(tmp.right);
                    }
                }
            }
            return sum;
        }
    }
  • 相关阅读:
    南京航空航天大学软件著作权申请办法
    CoDel Test Script
    [编辑中] 免费的Internet流量发生器 | Free Internet Traffic Generators
    关于Java LDAP登录集成
    sonar + ieda实现提交代码前代码校验
    sonar+Jenkins代码覆盖率检测
    定义自己的代码风格CheckStyle简单使用
    HAProxy简单使用
    读取大文件性能测试
    使用HtmlUnit登录百度
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10196092.html
Copyright © 2011-2022 走看看