Easy
113247FavoriteShare
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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its depth = 3.
C++:
/*
* @Author: SourDumplings
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/maximum-depth-of-binary-tree/
* @Date: 2019-03-03 17:02:38
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
int maxDepth(TreeNode *root)
{
return getHeight(root);
}
int getHeight(TreeNode *node)
{
if (!node)
{
return 0;
}
else
{
return max(getHeight(node->left), getHeight(node->right)) + 1;
}
}
};
Java:
/*
* @Author: SourDumplings
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/maximum-depth-of-binary-tree/
* @Date: 2019-03-03 17:07:13
*/
/**
* 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)
{
return getHeight(root);
}
public int getHeight(TreeNode node)
{
if (node == null)
{
return 0;
}
else
{
int lH = getHeight(node.left);
int rH = getHeight(node.right);
return lH > rH ? lH + 1 : rH + 1;
}
}
}