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;
}
}
相关文章推荐
- Leetcode 104. Maximum Depth of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- 【Leetcode】111. Minimum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- 【LeetCode】104. Maximum Depth of Binary Tree (2 solutions)
- [Leetcode] Binary tree-- 637. Average of Levels in Binary Tree
- [LeetCode] 111. Minimum Depth of Binary Tree
- 【LeetCode】111. Minimum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- [leetcode: Python]104. Maximum Depth of Binary Tree
- leetcode--111. Minimum Depth of Binary Tree
- 渣渣写LEETCODE——104. Maximum Depth of Binary Tree
- Leetcode 104. Maximum Depth of Binary Tree
- [LeetCode]104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetcode-104. Maximum Depth of Binary Tree
- python--leetcode226. Invert Binary Tree
- 剑指offer 面试题19:二叉树的镜像(leetcode226. Invert Binary Tree) 题解
- [Leetcode]@python 104. Maximum Depth of Binary Tree
- Leetcode-标签为Tree 111. Minimum Depth of Binary Tree