力扣,https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof/description/
class Solution {
public int calculateDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(calculateDepth(root.left), calculateDepth(root.right));
}
}
20180906整理
##Solution1:
再本题中树的定义:若二叉树只有一个根节点,则此二叉树的深度为1.
迭代法,哈哈哈
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot){
if(pRoot == NULL)
return 0;
else {
int res = GetTreeDepth(pRoot);
return res;
}
}
int GetTreeDepth(struct TreeNode *pRoot) {
if(pRoot == NULL)
return 0;
return 1 + max(GetTreeDepth(pRoot->left), GetTreeDepth(pRoot->right));
}
};