思路
一道巨简单的题目,单纯想练习一下递归。
复杂度
时间复杂度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 here
if(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;
}
}