标签:nbsp span append root length return turn class null
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 }
标签:nbsp span append root length return turn class null
原文地址:https://www.cnblogs.com/goPanama/p/9692275.html