题目

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.

题解

分析这道题,由根节点往叶节点方向走,就是从高位往地位加和的方向。也就是说,当遍历的节点往叶节点方向走一层的时候,该节点的值应为父节点的值*10+当前节点的值。

由此可以写出代码:

 1     int sumhelper(TreeNode root, int levelBase) {
 2         if(root == null)
 3             return 0;
 4             
 5         if(root.left == null && root.right == null) {
 6             return levelBase + root.val; 
 7         }
 8         
 9         int nextLevelBase = (levelBase + root.val)*10 ;
         int leftSubTreeSum = sumhelper(root.left, nextLevelBase);
         int rightSubTreeSum = sumhelper(root.right, nextLevelBase);
     
         return leftSubTreeSum + rightSubTreeSum;
     }
     
     public int sumNumbers(TreeNode root) {
         return sumhelper(root,0);
     }

最新文章

  1. 在Ubuntu 14.04安装和使用Docker
  2. jQuery中的事件处理
  3. mouseover和mouseout、mouseenter和mouseleave
  4. 黄聪:wkhtmtopdf--高分辨率HTML转PDF
  5. sql语句not in判断条件注意事项
  6. 折腾iPhone的生活——iPhone 5s 开启 assistive touch 后卡顿的问题
  7. hdoj 1686 Oulipo【求一个字符串在另一个字符串中出现次数】
  8. 深入浅出—JAVA(10)
  9. java-创建线程的两种方式
  10. 【web开发学习笔记】Structs2 Action学习笔记(一个)
  11. Python新式类继承的C3算法
  12. 配置mysql使其允许外部ip进行登录
  13. Android回调详解
  14. [BJOI2019]光线[递推]
  15. [Swift]LeetCode83. 删除排序链表中的重复元素 | Remove Duplicates from Sorted List
  16. 全志A33移植LCD驱动(ILI9806E)
  17. node 项目中 koa2 环境搭建 以及项目发布
  18. 阅读别人的程序(Java篇)
  19. DVWA的Xss跨站总结
  20. 【转】WCF光芒下的Web Service

热门文章

  1. INSTALL_FAILED_CONFLICTING_PROVIDER
  2. python基础-UDP、进程、进程池、paramike模块
  3. Codeforces Round #404 (Div. 2) A - Anton and Polyhedrons 水题
  4. VSCode换行符
  5. How to properly set clock speed for STM32F4xx devices
  6. Golang 特性简介
  7. 使用position:relative制作下边框下的小三角
  8. Complete uninstall on Mac, HELP!
  9. 使用jQuery实现图片懒加载原理
  10. Android 实现页面跳转并传递参数教程