The 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.
Notes:
- Basic question.
Java Solution
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxDepth(TreeNode root) { if(root== null) return 0; return getMax(root, 1); } private int getMax(TreeNode root, int depth){ if(root.left== null && root.right==null) return depth; int left=depth; int right = depth; if(root.left!= null) left = getMax(root.left, depth+1); if(root.right!= null) right = getMax(root.right, depth+1); return Math.max(left , right); } }
A simpler one.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxDepth(TreeNode root) { if(root== null) return 0; int left = maxDepth(root.left); int right = maxDepth(root.right); return Math.max(left, right)+1; } }
Advertisements