题解 | #二叉树的深度#
二叉树的深度
https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
解题思路
- 如果当前节点值为空,则返回0;
- 否则递归实现,每遍历一层增加层数1,并遍历左子树和右子树,选择大的一方。
复杂度
- 时间复杂度为O(N);
- 空间复杂度为O(N)。
代码
Python
class Solution: def TreeDepth(self , pRoot: TreeNode) -> int: if not pRoot: return 0 return 1+max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right))
C++
class Solution { public: int TreeDepth(TreeNode* pRoot) { if(pRoot == NULL) { return 0; } return 1+max(TreeDepth(pRoot->left), TreeDepth(pRoot->right)); } };