二叉树的深度

题目:

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。
提示:
节点总数 <= 10000

题目的理解:

一个二叉树的遍历问题。

python实现

# 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:
        deep = 0
        
        if root is not None:
            deep = 1
        
        children = list()
        children.append(root)

        while len(children) > 0:
            children_temp = list()
            for child in children:
                if child is not None:
                    if child.left is not None:
                        children_temp.append(child.left)
                    if child.right is not None:
                        children_temp.append(child.right)

            if len(children_temp) > 0:
                deep += 1

            children = children_temp

        return deep

提交

成功

// END 多动脑,不然脑子要老化了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容