Skip to content

Instantly share code, notes, and snippets.

@mding5692
Created September 29, 2016 04:46
Show Gist options
  • Save mding5692/d629c406c31f5b673ed4ac621ecfabbf to your computer and use it in GitHub Desktop.
Save mding5692/d629c406c31f5b673ed4ac621ecfabbf to your computer and use it in GitHub Desktop.
Western Tech Interview Prep Session #3
public class Solution {
public int sumNumbers(TreeNode root) {
if (root == null) {
return 0;
}
int sum = 0;
return dfs(root,sum);
}
public int dfs(TreeNode root, int sum) {
if (root == null) return 0;
if (root.left == null && root.right == null) {
//System.out.println(sum);
return concatIntStr(root.val,sum);
}
sum = concatIntStr(root.val,sum);
//System.out.println(sum);
return dfs(root.left, sum) + dfs(root.right, sum);
}
public int concatIntStr(int rootVal, int sum) {
String sumStr = Integer.toString(sum);
String rootValStr = Integer.toString(rootVal);
sumStr = sumStr + rootValStr;
sum = Integer.parseInt(sumStr);
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment