We're going to store numbers in a tree. Each node in this tree will store a single digit (from 0
to 9
), and each path from root to leaf encodes a non-negative integer.
Given a binary tree t
, find the sum of all the numbers encoded in it.
Link for the problem - https://app.codesignal.com/interview-practice/question/2oxNWXTS8eWBzvnRB/description
ArrayList<Long> list;
long solution(Tree<Integer> t) {
list = new ArrayList<>();
dfs(t, 0);
long sum = 0l;
for(int i=0; i<list.size(); i++) {
sum += (long)list.get(i);
}
return sum;
}
void dfs(Tree<Integer> root, long currSum) {
if(root==null)
return;
currSum = currSum*10 + root.value;
if(root.left==null && root.right==null) {
list.add(currSum);
}
if(root.left!=null)
dfs(root.left, currSum);
if(root.right!=null)
dfs(root.right, currSum);
currSum = currSum/10;
return;
}