当前位置: 代码迷 >> 综合 >> LintCode 481 Binary Tree Leaf Sum
  详细解决方案

LintCode 481 Binary Tree Leaf Sum

热度:81   发布时间:2023-10-28 04:35:31.0

思路

一道巨简单的题目,单纯想练习一下递归。

复杂度

时间复杂度O(n)
空间复杂度最坏情况O(n)

代码

/*** Definition of TreeNode:* public class TreeNode {* public int val;* public TreeNode left, right;* public TreeNode(int val) {* this.val = val;* this.left = this.right = null;* }* }*/public class Solution {
    /*** @param root: the root of the binary tree* @return: An integer*/public int leafSum(TreeNode root) {
    // write your code hereif(root == null)    return 0;if(root.left == null && root.right == null) {
    return root.val;}int sum = 0;sum += leafSum(root.left);sum += leafSum(root.right);return sum;}
}
  相关解决方案