Python实现"二叉树的最大深度"的两种方法

给定一棵二叉树,返回它的最大深度

最大深度是指树中最长路径所拥有的结点数量

注意:叶子节点没有子节点

例如:

给定二叉树[3,9,20,null,null,15,7]

  3
   / \
  9  20
    /  \
   15   7

它的返回值为3

1:从上到下按层级遍历二叉树,有多少层即二叉树有多深(方法类似:二叉树的层次遍历||https://mp.csdn.net/postedit/82352827)

def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        curLevelNodeList = [root]
        length = 0
        while curLevelNodeList:
            tempNodeList = [] 
            for node in curLevelNodeList:
                if node.left is not None:
                    tempNodeList.append(node.left)
                if node.right is not None:
                    tempNodeList.append(node.right)
            curLevelNodeList = tempNodeList
            length += 1
        return length

2:递归,比较每一条路径的长短

def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        left = self.maxDepth(root.left)+1
        right = self.maxDepth(root.right)+1
        
        return max(left, right)

算法题来自:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/

你可能感兴趣的:(Algorithms)