Leetcode - 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.
Analysis:
This problem can be easily solved using a recursive algorithm. As
maxDepth(root) = max(maxDepth(root.left), maxDepth(root.right) + 1 if root != null;
and maxDepth(root) == 0 if root == null;
Java solution:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//Definition for a binary tree node. class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } class MaxDepth { public int maxDepth(TreeNode root) { if(root == null) return 0; int leftMaxDepth = maxDepth(root.left); int rightMaxDepth = maxDepth(root.right); return Math.max(leftMaxDepth, rightMaxDepth) + 1; } } |
https://leetcode.com/problems/maximum-depth-of-binary-tree/











