Created
October 4, 2019 13:54
-
-
Save chaudharisuresh997/cfeefae6f227b591eb023ac7af3c45c5 to your computer and use it in GitHub Desktop.
Problem: sum root to leaf numbers https://www.interviewbit.com/problems/sum-root-to-leaf-numbers/
This file contains 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
/** | |
* Definition for binary tree | |
* class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { | |
* val = x; | |
* left=null; | |
* right=null; | |
* } | |
* } | |
*/ | |
import java.lang.*; | |
public class Solution { | |
float sum=0; | |
StringBuilder sb=new StringBuilder(); | |
ArrayList<Integer> list=new ArrayList<Integer>(); | |
int[] nodesArray=new int[256]; | |
// int counter=0; | |
//USING ARRAY | |
public void inorderArray(TreeNode A,int[] nodesArray,int counter){ | |
if(A==null){ | |
String resultNum=""; | |
if(nodesArray.length>1){ | |
for(int i=0;i<nodesArray.length;i++){ | |
resultNum=resultNum+""+nodesArray[i]; | |
} | |
if(resultNum!=null){ | |
if(resultNum!=""){ | |
System.out.println("resultNum "+resultNum); | |
//System.out.println("SUM "+sum); | |
float appendedNum=0; | |
try{ | |
appendedNum=Float.parseFloat(resultNum); | |
}catch(Exception e){ | |
// System.out.println("E"+resultNum); | |
} | |
sum=sum+appendedNum; | |
//if(list.length>1){ | |
// list.clear();//list.remove(list.size()-1); | |
//} | |
} | |
} | |
} | |
return; | |
} | |
// System.out.println("N"+A.val); | |
nodesArray[counter]=A.val; | |
counter++; | |
inorderArray(A.left,nodesArray,counter); | |
// System.out.println("::"+A.val); | |
inorderArray(A.right,nodesArray,counter); | |
} | |
public void inorder(TreeNode A,ArrayList<Integer> list){ | |
if(A==null){ | |
String resultNum=""; | |
if(list.size()>1){ | |
for(int i=0;i<list.size();i++){ | |
resultNum=resultNum+""+list.get(i); | |
} | |
if(resultNum!=null){ | |
if(resultNum!=""){ | |
System.out.println("resultNum "+resultNum); | |
//System.out.println("SUM "+sum); | |
float appendedNum=0; | |
try{ | |
appendedNum=Float.parseFloat(resultNum); | |
}catch(Exception e){ | |
// System.out.println("E"+resultNum); | |
} | |
sum=sum+appendedNum; | |
if(list.size()>1){ | |
list.clear();//list.remove(list.size()-1); | |
} | |
} | |
} | |
} | |
return; | |
} | |
// System.out.println("N"+A.val); | |
list.add(A.val); | |
inorder(A.left,list); | |
// System.out.println("::"+A.val); | |
inorder(A.right,list); | |
} | |
public int sumNumbers(TreeNode A) { | |
if(A==null){ | |
}else{ | |
if(A.left==null && A.right==null){ | |
sum=A.val; | |
}else{ | |
inorderArray(A,nodesArray,0); | |
} | |
//processNumbers(A,sb); | |
} | |
//System.out.println("FINAL"+sum); | |
return (int)sum%1003; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment