zoukankan      html  css  js  c++  java
  • LeetCode OJ: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.

    简单的用递归就可以实现,代码如下:

     1 class Solution {
     2 public:
     3     int sumNumbers(TreeNode* root) {
     4         dfs(root, 0);
     5     }
     6 
     7     int dfs(TreeNode * root, int curr){
     8         if(!root)
     9             return 0;
    10         if(!root->left && !root->right)
    11             return curr * 10 + root->val;
    12         return dfs(root->left, curr    * 10 + root->val) + dfs(root->right, curr * 10 + root->val);
    13     }
    14 };

    java版本的代码如下所示:

     1 public class Solution {
     2     public int sumNumbers(TreeNode root) {
     3         return dfs(root, 0);
     4     }
     5 
     6     public int dfs(TreeNode root, int curr){
     7         if(root == null)
     8             return 0;
     9         if(root.left == null && root.right == null)
    10             return curr * 10 + root.val;
    11         return dfs(root.left, curr * 10 + root.val) + dfs(root.right, curr * 10 + root.val);
    12     }
    13 }
  • 相关阅读:
    django显示SQL语句
    AngularJS国际化配置
    Django的国际化
    21天实战caffe笔记_第二天
    图像处理之CSC性能优化(源码)
    图像处理之CSC色彩转换
    21天实战caffe笔记_第一天
    图像处理之色彩转换(CCM)
    图像处理之FPN校正
    图像处理之坏点校正及源码实现
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4910721.html
Copyright © 2011-2022 走看看