zoukankan      html  css  js  c++  java
  • 【剑指offer】面试题55

    题目描述

    面试题55 - I. 二叉树的深度

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

    例如:

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

        3
       /
      9  20
        / 
       15   7

    返回它的最大深度 3 。

    分析

    1.广度优先遍历 BFS

    和上几道题层次遍历一个思路,采用先入先出的队列数据结构,初始化一个dep变量,每加一层加一

    2.深度优先搜索(DFS)

    用到递归,深度为根节点左右子树的深度max+1

    解题

    1.

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def maxDepth(self, root: TreeNode) -> int:
            if(not root):
                return 0
            temp=[root]
            dep=0
            while(temp):
                dep+=1
                length = len(temp)
                for i in range(length):
                    cur=temp.pop(0)
                    if(cur.left):
                        temp.append(cur.left)
                    if(cur.right):
                        temp.append(cur.right)  
            return dep

    2.

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def maxDepth(self, root: TreeNode) -> int:
            if(not root):
                return 0
            return max(self.maxDepth(root.left), self.maxDepth(root.right))+1
  • 相关阅读:
    c语言命名规则 [转载]
    [转贴]C编译过程概述
    [转贴]漫谈C语言及如何学习C语言
    Semaphore源码分析
    如何快速转行大数据
    web前端到底怎么学?
    Code Review怎样做好
    SDK与API的理解
    分析消费者大数据
    程序员的搞笑段子
  • 原文地址:https://www.cnblogs.com/fuj905/p/12910088.html
Copyright © 2011-2022 走看看