• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

主要是看你如何设计这个Recursion 这是一道树的题目,一般使用递归来做,主要就是考虑递归条件和结束条件。想到这样设计Recursion其实还挺难的

 1 public class Solution {
 2     public int sumNumbers(TreeNode root) {
 3         if (root == null) return 0;
 4         return helper(root, 0);
 5     }
 6     
 7     public int helper(TreeNode root, int sum) {
 8         if (root.left==null && root.right==null) return 10*sum+root.val;
 9         else if (root.left == null) return helper(root.right, 10*sum+root.val);
10         else if (root.right == null) return helper(root.left, 10*sum+root.val);
11         else {
12             return helper(root.left, 10*sum+root.val) + helper(root.right, 10*sum+root.val);
13         }
14     }
15 }

推荐做法:

 1 public int sumNumbers(TreeNode root) {
 2     return helper(root,0);
 3 }
 4 private int helper(TreeNode root, int sum)
 5 {
 6     if(root == null)
 7         return 0;
 8     if(root.left==null && root.right==null)
 9         return sum*10+root.val;
10     return helper(root.left,sum*10+root.val)+helper(root.right,sum*10+root.val);
11 }

 

posted @ 2014-09-21 06:47  neverlandly  阅读(477)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3