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 语言常用算法详解-排序-队列-堆栈-链表-递归-树 (面试有用)
    iOS多线程各种安全锁介绍
    将openfire部署到CentOS云服务器上
    触摸事件MultiTouch Events
    Usaco 2006Nov Round Numbers
    Codeforces 850C Arpa and a game with Mojtaba
    HDU4466 Triangle
    Codeforces Gym 101521A Shuttle Bus
    Codeforces 817F MEX Queries
    Codeforces 482B Interesting Array
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10196092.html
Copyright © 2011-2022 走看看