Lintcode481-Binary Tree Leaf Sum-Easy

481. Binary Tree Leaf Sum

Given a binary tree, calculate the sum of leaves.

Example

Example 1:

Input:
    1
   / 
  2   3
 /
4
output:7.

Example 2:

Input:
    1
      
       3
Output:3.


注意:
sum是类成员变量的原因:因为没执行一次递归,递归方法里的局部变量都会被重新创建。在递归函数中,不需要每次都创建sum,只有访问叶子结点时,对sum操作即可。

递归过程详解(讲解很透彻,包括递归中的return过程,递归的终止条件)
理解递归,关键是脑中有一幅代码的图片,函数执行到递归函数入口时,就扩充一段完全一样的代码,执行完扩充的代码并return后,继续执行前一次递归函数中递归函数入口后面的代码

递归法代码:

/**
 * 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
     */
    int sum = 0;
    public int leafSum(TreeNode root) {
        helper(root);
        return sum;
    }
    public void helper(TreeNode root) {
        if (root == null) {
            return;
        }
        
        if (root.left == null && root.right == null) {
            sum += root.val;
            return;
        }
        
        helper(root.left);
        helper(root.right);
    }
}
原文地址:https://www.cnblogs.com/Jessiezyr/p/10661448.html