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;
        }
    }
  • 相关阅读:
    JS中关于clientWidth offsetWidth scrollWidth 等的含义
    javascript中数组concat()join()split()
    我的大数据学习路线(持续更新)
    java多线程-学习笔记
    java多线程-线程交互&互斥&同步
    java多线程-关键人物程咬金
    java多线程-军队战争
    java多线程-两个演员线程
    pytorch-Flatten操作
    龙良曲pytorch学习笔记_迁移学习
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10196092.html
Copyright © 2011-2022 走看看