LintCode 97. 二叉树的最大深度
题目链接:https://www.lintcode.com/problem/maximum-depth-of-binary-tree/description
描述:给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的距离。
分别使用迭代和分治两种递归方法做了一下题目,题目较简单,直接记录一下代码实现:
/**
* 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
*/
/*//递归的定义
void findMaxDepth(TreeNode *root, int curtdepth, int *MAXDepth){
//递归的出口
if(root == NULL){
return;
}
if(curtdepth > *MAXDepth){
*MAXDepth = curtdepth;
}
//递归的拆解
findMaxDepth(root->left, curtdepth + 1, MAXDepth);
findMaxDepth(root->right, curtdepth + 1, MAXDepth);
}*/
int maxDepth(TreeNode * root) {
/*//1、Traversal方法
int MAXDepth = 0;
//递归的调用
findMaxDepth(root, 1, &MAXDepth);
return MAXDepth;*/
//2、分治算法
int MAXDepth = 0;
//递归的出口
if(root == NULL){
return MAXDepth;
}
MAXDepth = MAXDepth + 1;
//递归的拆解
int leftdepth = maxDepth(root->left);
int rightdepth = maxDepth(root->right);
MAXDepth = leftdepth > rightdepth ? leftdepth : rightdepth;
return MAXDepth + 1;
}
};