129. Sum Root to Leaf Numbers
Posted gopanama
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了129. Sum Root to Leaf Numbers相关的知识,希望对你有一定的参考价值。
1 //New 2 class Solution { 3 public int sumNumbers(TreeNode root) { 4 if(root == null) return 0; 5 return dfs(root, 0); 6 7 } 8 9 public int dfs(TreeNode root, int sum) { 10 if(root == null) return 0; 11 if(root.left == null && root.right == null) { 12 return sum*10 + root.val; 13 }else { 14 return dfs(root.left, sum*10 + root.val) + dfs(root.right, sum*10 + root.val); 15 } 16 17 } 18 } 19 20 21 22 23 24 //Old 25 class Solution { 26 int sum = 0; 27 public int sumNumbers(TreeNode root) { 28 if(root == null) return 0; 29 dfs(root, new StringBuilder()); 30 return sum; 31 32 } 33 34 public void dfs(TreeNode root, StringBuilder sb) { 35 if(root == null) return; 36 if(root.left == null && root.right == null) { 37 sb.append(root.val); 38 sum += Integer.parseInt(sb.toString()); 39 sb.deleteCharAt(sb.length() - 1); 40 }else { 41 sb.append(root.val); 42 dfs(root.left, sb); 43 dfs(root.right, sb); 44 sb.deleteCharAt(sb.length() - 1); 45 } 46 47 } 48 }
以上是关于129. Sum Root to Leaf Numbers的主要内容,如果未能解决你的问题,请参考以下文章