题解 | #二叉树的深度#
二叉树的深度
https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pRoot TreeNode类 # @return int整型 # class Solution: def TreeDepth(self , pRoot: TreeNode) -> int: # write code here if not pRoot: return 0 if pRoot.left is None and pRoot.right is None: return 1 return max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right))+1
以上方法用递归,空间O(N),但题目要求O(1)。
递归思路:找最深左子树或最深右子树的高度
ref:
https://blog.nowcoder.net/n/17332a8453f442f8b4cade938903de5d