leetcode104-- Maximum Depth of Binary Tree (求二叉树的深度)

leetcode104-- Maximum Depth of Binary Tree (求二叉树的深度)

先用递归的办法,比较容易

# 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

非递归的解法, 层次遍历(利用队列来实现)

# 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
        queue = []   # 申请一个队列
        queue.append(root)
        level = 0   # 结果初始化
        while len(queue) >0:   # 当队列不空的时候
            cur_len = len(queue)   # 得到当前层的长度
            level += 1          # 深度加1     
            while cur_len:  # 只要当前这一层的没有用完的时候,就把第一个给弹出来, 同时要看看它有没有左右子树,有的话就放入队列中去.
                front = queue.pop(0)
                if front.left:
                    queue.append(front.left)
                if front.right:
                    queue.append(front.right)
                cur_len -= 1

        return level

打赏,谢谢~~

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,多谢支持~

打开微信扫一扫,即可进行扫码打赏哦