[Leetcode 8] 104 Maximum Depth of Binary Tree
Problem:
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:
Recursion can solve it.
The time complexity is O(h).
Code:
View Code
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int maxDepth(TreeNode root) { 12 // Start typing your Java solution below 13 // DO NOT write main() function 14 return depth(root, 0); 15 } 16 17 private int depth(TreeNode t, int dep) { 18 if (t == null) 19 return dep; 20 else 21 return max(depth(t.left, dep+1), depth(t.right, dep+1)); 22 } 23 24 private int max (int a, int b) { 25 return a>b?a:b; 26 } 27 }
Attention: