zoukankan      html  css  js  c++  java
  • leetcode二叉树404. 左叶子之和

    考点 左叶子,无左右节点的节点才叫叶子

    
    package binarytree.sumOfLeftLeaves;
    
    import binarytree.untils.GenerateTreeNode;
    import binarytree.untils.TreeNode;
    
    /**
     * 404. 左叶子之和
     * 计算给定二叉树的所有左叶子之和。
     *
     * 示例:
     *
     *     3
     *    / \
     *   9  20
     *     /  \
     *    15   7
     *
     * 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
     *
     */
    public class sumOfLeftLeaves {
        /**
         * 遍历全路径,累计左节点值
         *
         * 前序遍历
         * @param root
         * @return
         */
        public static int sumOfLeftLeaves(TreeNode root) {
    
            if(root == null){
                return 0;
            }
    
            int res = 0;
    
            if(root.left!=null&&root.left.left == null && root.left.right == null){
                res+=root.left.val;
            }
    
            return sumOfLeftLeaves(root.right) + sumOfLeftLeaves(root.left) + res;
        }
    
    
    
        public static void main(String[] args) {
            Integer[] nums = {1,2,3,4,5};
            TreeNode treeNode = GenerateTreeNode.generateTreeNode(nums);
            int sum = sumOfLeftLeaves(treeNode);
            System.out.println(sum);
        }
    }
    
    
  • 相关阅读:
    Ubuntu 18.04 初始化(server版本 )
    named主从环境部署
    CentOS 源码安装svn
    端口状态
    进程状态
    top命令详解
    gitlab部署
    day16
    day15
    day14
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/15700908.html
Copyright © 2011-2022 走看看