标签:
题目:
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.
题解:
与minimum代码几乎完全一样,只需要修改math.min为math.max
1 public class Solution { 2 public int maxDepth(TreeNode root) 3 { 4 int depth=0; 5 depth=depthHelper(root,depth); 6 return depth; 7 } 8 9 public int depthHelper(TreeNode root, int depth) 10 { 11 if(root==null) 12 return 0; 13 14 depth+=1; 15 if(root.left!=null&&root.right!=null) 16 { 17 return Math.max(depthHelper(root.left,depth),depthHelper(root.right,depth)); 18 } 19 else if (root.left==null&&root.right!=null) 20 { 21 return depthHelper(root.right,depth); 22 } 23 else if(root.left!=null&&root.right==null) 24 { 25 return depthHelper(root.left,depth); 26 } 27 else return depth; 28 29 } 30 }
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4703660.html