Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def calculateDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(self.calculateDepth(root.left), self.calculateDepth(root.right))
Java
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));
}
};