欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

左叶子之和

程序员文章站 2022-07-14 18:24:48
...

计算给定二叉树的所有左叶子之和。

示例:

    3
   / \
  9  20
    /  \
   15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

 

解题思路:

递归遍历所有节点 ,

当当前节点的左孩子不空,左孩子没有孩子的(即没有左节点和右节点)

那么加上这个值,就是左叶子节点

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int result=0;
    public int sumOfLeftLeaves(TreeNode root) {

        if(root==null){
            return 0;
        }

    //that 's left leaves
    // current leaves  leftleaves  is not null   
    //leftleaves leftleaves is null   and leftleaves rigthleaves is null  
    if(root.left!=null&&(root.left.left==null&&root.left.right==null)){

        result=result+root.left.val;
    }

    sumOfLeftLeaves(root.left);
    sumOfLeftLeaves(root.right);

return result;
    }
}

 

 

相关标签: 数据结构和算法