Created
September 29, 2016 04:46
-
-
Save mding5692/d629c406c31f5b673ed4ac621ecfabbf to your computer and use it in GitHub Desktop.
Western Tech Interview Prep Session #3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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