码迷,mamicode.com
首页 > 其他好文 > 详细

Maximum Depth of Binary Tree

时间:2015-08-05 07:44:48      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

题目

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 }

 

Maximum Depth of Binary Tree

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4703660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!