Monday, July 10th
A simple binary tree traversal is the topic of today's problem
Given the root node of a binary tree, find the length to the closest leaf node
My solution wasn't pretty, but got the job done
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
else if(root->right==NULL && root->left==NULL) return 1;
int resl=minDepth(root->left);
int resr=minDepth(root->right);
if( resl && resr) {
return 1+min(resl,resr);
} else if( resl ) {
return 1+resl;
} else if( resr ) {
return 1+resr;
} else {
return 0;
}
}
Definitely room for improvement
Arguments were made that BFS may be a better approach here, because of less memory usage and that the first leaf node found will be the closest, but recursion can be more fun
I had to step away from the problem for a few minutes before sitting back down and solving it. Maybe should change my approach to Problems of the Day and allow more time to mull it over than just giving 15 minutes of thought
Comments
Post a Comment