Just a bit shorter/different than previous solutions.
def max_depth(root) root ? 1 + [max_depth(root.left), max_depth(root.right)].max : 0 end
def maxDepth(self, root): return 1 + max(map(self.maxDepth, (root.left, root.right))) if root else 0
@StefanPochmann This concise solution makes it tad slow. Any comments?
def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root==None: return 0 leftChildHeight=self.maxDepth(root.left) rightChildHeight=self.maxDepth(root.right) return max(leftChildHeight, rightChildHeight)+1
This one is like 20 ms faster. I don't understand the reason though.
@kaddu I don't see that being faster. How often did you submit each and what were the individual times?
@StefanPochmann Submitted each once only. One was 55ms and the other was 78ms. How does the OJ really work with the timing? I have noticed its mischievous at times.
@kaddu Once is not nearly enough. Especially with Python, where the system/judge usually take much of the time and that varies quite a bit. I think Java might still be the only language where the judge time is excluded (because earlier the Java judge time was very high (like 400 ms) and varying a lot as well, so an effort was made to fix that). I suggest you play around with solutions in several languages a bit, submit them several times and observe the acceptance time ranges to get a feeling for this.
I wrote an even shorter python version just for fun :)
It's 2 characters shorter than yours.
def maxDepth(self, root): return root and 1 + max(map(self.maxDepth, (root.left, root.right))) or 0
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.