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

     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     public int sumNumbers(TreeNode root) {
    12         // IMPORTANT: Please reset any member data you declared, as
    13         // the same Solution instance will be reused for each test case.
    14         ArrayList<Integer> result = new ArrayList<Integer>();
    15         if(root == null)
    16             return 0;
    17         dfs(result, 0, root);
    18         int sum = 0;
    19         for(int i:result)
    20             sum += i;
    21         return sum;
    22     }
    23     
    24     private void dfs(ArrayList<Integer> result, int now, TreeNode root){
    25         if(root.left == null && root.right == null){
    26             result.add(10*now+root.val);
    27             return;
    28         }
    29         now = now * 10 + root.val;
    30         if(root.left!=null)
    31             dfs(result, now, root.left);
    32         if(root.right!=null)
    33             dfs(result, now, root.right);
    34     }
    35 }
  • 相关阅读:
    数据分析(三)
    数据分析(二)
    数据分析(一)
    sql server 脚本创建数据库和表
    各种距离分析
    DataTable数据导出CSV文件
    WPF中Grid布局
    111
    123
    SVN的安装与使用
  • 原文地址:https://www.cnblogs.com/jasonC/p/3411711.html
Copyright © 2011-2022 走看看