您的位置:首页 > 其它

leetcode 104. Maximum Depth of Binary Tree

2016-08-01 15:41 489 查看


104. Maximum Depth of Binary Tree

 

Question
Editorial Solution
 My Submissions

Total Accepted: 163149
Total Submissions: 333194
Difficulty: Easy

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.

Subscribe to see which companies asked this question

Show Tags

Show Similar Problems

Have you met this question in a real interview? 

Yes
 

题意:输出二叉树的最深节点,那么我们直接将这棵树遍历一遍就可以啦,注意判断节点是否为空(包括根节点),否则会抛NULLPointerException,遍历树当然是使用递归的方式啦,还是很简单的题目的,好久都没做题了,现在试一试Java来做题,代码以下

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
int ans=1;
if(root!=null)
{
if (root.left != null) ans = Math.max(ans, maxDepth(root.left) + 1);
if (root.right != null) ans = Math.max(ans, maxDepth(root.right) + 1);
}
else
{
ans=0;
}
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: