55-I. The depth of the binary tree (simple)

Title description:

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)
形成树的一条路径,最长路径的长度为树的深度。

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

    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。

Idea 1: BFS

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        # BFS
        if not root:return 0
        res=[]
        count=0
        res.append(root)
        while res:
            length=len(res)
            for i in range(length):
                node=res.pop(0)
                if node.left:res.append(node.left)
                if node.right:res.append(node.right)
            count+=1
        return count

Idea 2: Recursion

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        #递归
        if not root:return 0
        count =max(self.maxDepth(root.left),self.maxDepth(root.right)) +1
        return count

 

Guess you like

Origin blog.csdn.net/weixin_38664232/article/details/104997270