I am trying to find the maximum sum of value from root to leaf nodes in a binary tree using stack. I wrote the following code but there is a bug in it . <>
Stacks s;
s.push(root);
maxSum=currSum=0;
while(!s.isEmpty()) {
temp = s.top();
s.pop();
if( temp->left == null && temp->right == null ) {
currSum = currSum+temp->data;
if(currSum > maxSum) {
maxSum = currSum;
}
currSum =0;
} else {
currSum = currSum + temp->data;
if(temp->left) s.push(temp->left);
if(temp->right) s.push(temp->right);
}
}
What I am trying to do is calculate the sum till the leaf node and assign it to maxSum.
Ex:- Binary tree is
1
/ \
2 3
/ \
4 5
1)I first push 1 and pop . currSum =1;
2) Push 3 and 2 and pop 2. cursum = 3 and push 5 and 4;
3) Stack now looks like 4<-5-<3-<1 (4 is top element)
4)Now as 4 is leaf node , I enter the if loop
and add currSum = 3+4=7 and pop 4 .
5)Now temp is 5 and I set currSum=0, so currSum when I pop 5 becomes 5 .
Can anyone help me fix this bug please
Consider this example for your code.
The Code below will help you through. Try using stack in place of vector.
using namespace std;