给出一棵如下的二叉树:
1
/ \
2 3
…/ \
…4 5
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int maxDepth(TreeNode *root) {
// write your code here
if(root == NULL) return 0;
int leftMax = maxDepth(root ->left);
int rightMax = maxDepth(root ->right);
return max(leftMax,rightMax) + 1;
}
};
最小深度
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int minDepth(TreeNode *root) {
// write your code here
if(root == NULL) return 0;
int res = helper(root);
return res;
}
int helper(TreeNode* root) {
if (root == NULL) return INT_MAX; //为空时,不能算深度
if(root ->left == NULL && root ->right == NULL) return 1; //叶结点深度为1
int left = helper(root ->left);
int right = helper(root ->right);
return min(left,right) + 1;
}
};