I'm doing some firecode questions to prepare for coding interviews, and I'm struggling to figure out what's wrong with this code. The goal is to find the minimum sum path from root to leaf. The example tree in attached pic should return 10, but it's returning 14. Can someone help me understand why? I'm not great at recursion.
public int findHeight(TreeNode root) {
if(root == null)
return 0;
int l = findHeight(root.left);
int r = findHeight(root.right);
if(l == 0 && r != 0) return root.data+r;
if(l != 0 && r == 0) return root.data+l;
return root.data+Math.min(l, r);
}
works for me, maybe you have the tree wrong
>>62161826
Works for me (sorry for shitty code I never use C and wanted to see if I could do it)#include <stdio.h>
int min(int l, int r) {
return l<r ? l : r;
}
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
int findHeight(struct TreeNode* root) {
if(root == NULL)
return 0;
printf("%d\n", root->data);
int l = findHeight(root->left);
int r = findHeight(root->right);
if(l == 0 && r != 0) return root->data+r;
if(l != 0 && r == 0) return root->data+l;
return root->data+min(l, r);
}
int main() {
struct TreeNode root = {6};
struct TreeNode four = {4};
struct TreeNode seven = {7};
struct TreeNode eight = {8};
eight.left = &seven;
root.left = &four;
root.right = &eight;
printf("%d\n", findHeight(&root));
}
Returns 10
Thanks guys, I'm just going to assume it's an issue with the way their tested builds the tree then because my code logically makes sense. Plus, you guys have pretty much verified it.