- 题目描述:
- 题目链接:
详细操作流程看下图
-视频讲解链接B站视频讲解
- 代码:
c++版本:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
int maxDepth(TreeNode* root) {
if(root == NULL) return 0; //根点为空返回0
int lh = maxDepth(root->left); // 求出左子树的最大高度
int rh = maxDepth(root->right); //求出右子树的最大高度
return max(lh,rh) + 1; //左右子树高度求一个最大然后+1
}
};
Java版本:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public int maxDepth (TreeNode root) {
if(root == null) return 0; //节点为空返回0
int lh = maxDepth(root.left); // 求出左子树的最大高度
int rh = maxDepth(root.right); //求出右子树的最大高度
return Math.max(lh,rh) + 1; //左右子树高度求一个最大然后+1
}
}Python版本:
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类
# @return int整型
#
class Solution:
def maxDepth(self , root ):
# write code here
if not root : return 0 #节点为空返回0
lh = self.maxDepth(root.left) #求出左子树的最大高度
rh = self.maxDepth(root.right) #求出右子树的最大高度
return max(lh,rh) + 1 #左右子树高度求一个最大然后+1

京公网安备 11010502036488号