牛客网-二叉树的深度

 

利用二叉树的层次遍历:用计数判断层数是否发生改变

class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        if pRoot==None:
            return 0
        quene = [pRoot]
        count = 0
        nextcount = 1
        depth = 0
        while(quene):
            root = quene.pop(0)
            count += 1
            if root.left:
                quene.append(root.left)
            if root.right:
                quene.append(root.right)
            if count == nextcount:
                nextcount = len(quene)
                count = 0
                depth += 1
        return depth

利用二叉树的前序遍历:

#求二叉树的深度
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
posted @ 2019-12-29 12:26  ditingz  阅读(202)  评论(0编辑  收藏  举报