利用二叉树的前序遍历:
#求二叉树的深度 class Solution: def TreeDepth(self, pRoot): if pRoot==None: return 0 result = 0 count = 0 stack = [(pRoot,1)] while(stack): root,count = stack.pop() if root.right: stack.append((root.right,count+1)) if root.left: stack.append((root.left,count+1)) if root.right==None and root.left==None and result<count: result = count return result
还有自己写不出来,看了下别人的才发现那么简单的递归
class Solution: def TreeDepth(self, pRoot): # write code here if pRoot==None: return 0 left = self.TreeDepth(pRoot.left) right = self.TreeDepth(pRoot.right) return left+1 if left>right else right+1