Leetcode 104. Maximum Depth of Binary Tree

Leetcode 104. Maximum Depth of Binary Tree

题目描述:找出二叉树的最大深度。

题目链接:Leetcode 104. Maximum Depth of Binary Tree

思路:递归的做法就是不断返回二叉树的左子树右子树深度比较大的那一个。
迭代的做法就是,用hashmap记录每个节点的深度,然后不断遍历的过程中更新ans,最后加上根节点的深度。
也可以层序遍历,看深度。

代码如下

  def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        s = [root]
        hm = {None:0}
        ans = 0 #包括根节点
        while(s):
            t = s.pop()
            if t:
                left = hm.get(t.left)
                right = hm.get(t.right)
                if(left is not None and right is not None):
                    hm[t] = max(left,right) + 1
                    ans = max(ans,left,right)
                else:
                    s.extend([t,t.right,t.left])
        return ans+1

参考链接