分治法 二叉树的最大深度
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 ld = maxDepth(root->left);
int rd = maxDepth(root->right);
int depth = max(ld,rd);
return depth+1;
}
};
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;}
return getDepth(root);
}
int getDepth(TreeNode *root){
int depth = 0;
if(root == NULL){
return 0;
}
if(root->left == NULL && root->right == NULL){
return 1;
}
else if(root->left == NULL && root->right != NULL){
depth = getDepth(root->right)+1;
}
else if(root->left != NULL && root->right == NULL){
depth = getDepth(root->left )+1;
}
else{
depth = min(getDepth(root->left),getDepth(root->right))+1;
}
return depth;
}}