0%

leetCode-104:Maximum Depth of Binary Tree

问题描述

给定一个二叉树,要求算出二叉树的高度。题目链接:**点我**

样例输入输出

输入:[1, 2, null, 3]

输出:3

解释:二叉树如下

1

/

2

/

3

输入:[1]

输出:1

问题解法

递归计算子树的高度,取其最大值加一,即是二叉树的高度。代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution
{
public int maxDepth(TreeNode root)
{
if (root == null)
{
return 0;
}

return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}