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 }
  • 相关阅读:
    Chrome浏览器与常用插件推荐
    时间戳 转换24小时制
    fis3 开启相对地址
    web手机端禁止滑动,web手机端禁止上下滑动。
    rem的用法
    手机端复制,pc端复制
    ruby 镜像安装
    使用Potree渲染大规模点云-踩坑记录
    移动端真机调试神器-spy-debugger
    手撕Promise.any
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4910721.html
Copyright © 2011-2022 走看看