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.
    

    求二叉树左边叶子的和

    public int sumOfLeftLeaves(TreeNode root) {
            if(root == null) return 0;
            int sum=0;
            if(root.left != null)
            {
                if(root.left.left == null && root.left.right == null) 
                    sum += root.left.val;
                else
                    sum += sumOfLeftLeaves(root.left);
            }
            sum += sumOfLeftLeaves(root.right);
            return sum;
            
        }
    

    这类题目无非就是对二叉树的遍历上面做文章,最简单的方法就是递归求解,牢记遍历时候的套路。下面是使用非递归方式,借用stack

    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;
    }
    
  • 相关阅读:
    字符串动手动脑
    类与对象课后思考
    java动手动脑课后思考题
    java思考题
    《大道至简第二章读后感》
    从命令行接收多个数字,求和之后输出结果
    《大道至简》读后感
    团队项目成员和题目
    软件工程个人作业04
    软件工程个人作业03
  • 原文地址:https://www.cnblogs.com/wxshi/p/7649054.html
Copyright © 2011-2022 走看看