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;
        }
    }
  • 相关阅读:
    C++
    C语言获取系统时间的几种方式
    我在学习编程中犯的两个最大错误
    《十天学会单片机和C语言编程》
    socket 编程通信实例
    比尔·盖茨给年轻人的十一个忠告 句句是哲理
    程序员有八个级别。
    DOS debug 命令的详细用法
    从命令行模式运行Windows管理工具。
    无法删除DLL文件解决方法(转)
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10196092.html
Copyright © 2011-2022 走看看