Monday, February 15, 2016

Leetcode: Max Depth of Binary Tree

Difficulty: Easy

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.

Runtime Analysis:
Runtime: O(n)
Space: O(h)
Algorithmic Approach:
Question requires a basic understanding of Binary Trees. At each step, if the node is null, then we return a height of 0. Otherwise, we return 1 + the max height of the left and right children. 
Java Code:
public class Solution { public int maxDepth(TreeNode root) { if(root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
} }

No comments:

Post a Comment