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));
}
};
本文介绍了如何使用递归方法计算二叉树的深度,并提供了两种不同的实现方式。一种是Java版本的实现,另一种是C++版本的实现。通过这两种方法可以有效地计算出二叉树的深度。
246

被折叠的 条评论
为什么被折叠?



