zoukankan      html  css  js  c++  java
  • leetcode------Sum Root to Leaf Numbers

    标题: Sum Root to Leaf Numbers
    通过率: 30.4%
    难度: 中等

    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.

    整个过程是深度优先,然后每下一层就放大十倍,那么如果是叶子节点则与sum相加,其他时候继续往下搜索,代码如下:

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     int sum;
    12     public int sumNumbers(TreeNode root) {
    13         sum=0;
    14         if(root==null)return 0;
    15         dfs(root,0);
    16         return sum;
    17     }
    18     public void dfs(TreeNode root,int num){
    19         num=num*10+root.val;
    20         if(root.right==null&&root.left==null) sum+=num;
    21         if(root.left!=null) dfs(root.left,num);
    22         if(root.right!=null) dfs(root.right,num);
    23         
    24     }
    25 }
  • 相关阅读:
    有没有用户体验+UI+前端集于一身的人
    ruby array.count
    ruby subset
    向李刚同学道歉
    rails3转载
    RVM and Capistrano
    paperclip自定制文件名
    ruby爬虫
    rails3已经内置subdomain
    摘录
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4350787.html
Copyright © 2011-2022 走看看