Leetcode 129) Sum Root to Leaf Numbers
in Algorithms
My Answer
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int res=0;
public int sumNumbers(TreeNode root) {
helper(0 , root);
return res;
}
public void helper(int prev , TreeNode tn){
int cur=prev*10+tn.val;
//basecase
if(tn.left ==null && tn.right==null){
res += cur;
return;
}
if(tn.left!=null){
//tn.left!=null
helper(cur,tn.left);
}
if(tn.right!=null){
helper(cur,tn.right);
}
}
}
Other Answer
class Solution {
int rootToLeaf = 0;
public void preorder(TreeNode r, int currNumber) {
if (r == null) {
return;
}
if (r != null) {
currNumber = currNumber * 10 + r.val;
// if it's a leaf, update root-to-leaf sum
if (r.left == null && r.right == null) {
rootToLeaf += currNumber;
return;
}
preorder(r.left, currNumber);
preorder(r.right, currNumber) ;
}
}
public int sumNumbers(TreeNode root) {
preorder(root, 0);
return rootToLeaf;
}
}