剑指offer-二叉树的深度(python)

思路一:递归

class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        if pRoot is None:
            return 0
        left=self.TreeDepth(pRoot.left)
        right=self.TreeDepth(pRoot.right)
        count = max(left,right) + 1
        return count

思路二:dfs

class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        """
        if pRoot is None:
            return 0
        left=self.TreeDepth(pRoot.left)
        right=self.TreeDepth(pRoot.right)
        count = max(left,right) + 1
        return count
        """
        res=[]
        cnt=0
        if pRoot is None:
            return 0
        tmp=[pRoot]
        while tmp:
            for node in tmp:
                if node.left is not None:
                    res.append(node.left)
                if node.right is not None:
                    res.append(node.right)
            cnt+=1
            tmp=res
            res=[]
        return cnt

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104441390