I'm working on this leetcode problem:
https://leetcode.com/problems/maximum-depth-of-binary-tree/
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Working Code:
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
if(left > right)
return left + 1;
else
return right + 1;
}
}
Non-working Code:
public class Solution {
int left = 0;
int right = 0;
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
left = maxDepth(root.left);
right = maxDepth(root.right);
if(left > right)
return left + 1;
else
return right + 1;
}
}
Could someone explain why one doesn't work? Recursion hurts my head.