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);
    }
}

原文地址:https://www.cnblogs.com/xiaoshahai/p/15700908.html