LeetCode OJ - Sum Root to Leaf Numbers

时间:2014-04-28 10:05:40   收藏:0   阅读:682

这道题也很简单,只要把二叉树按照宽度优先的策略遍历一遍,就可以解决问题,采用递归方法越是简单。

下面是AC代码:

bubuko.com,布布扣
 1 /**
 2      * Sum Root to Leaf Numbers 
 3      * 采用递归的方法,宽度遍历
 4      */
 5     int result=0;
 6     public int sumNumbers(TreeNode root){
 7         
 8         bFSearch(root,0);
 9         return result;
10     }
11     private void bFSearch(TreeNode root, int sum){
12         //a path has been finished
13         if(root.left == null && root.right == null)
14         {
15             result += sum*10+root.val;
16             return;
17         }
18         if(root.left !=null)
19             bFSearch(root.left,  sum*10+root.val);
20         if(root.right != null)
21             bFSearch(root.right,  sum*10+root.val);
22     }
bubuko.com,布布扣

 

LeetCode OJ - Sum Root to Leaf Numbers,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!