Leetcode刷题记录——662. 二叉树最大宽度

在这里插入图片描述
在这里插入图片描述
我们将每一层的最左侧索引和最右侧索引记录为一个元组,放在一个全局变量list里
我们设计一个函数用于递归
其输入是 新递归到的节点root、其父节点在上一层(父节点自己那层)从左往右数是第几个index、自己这层的深度depth 以及自己是父节点的左孩子还是右孩子direction(int,左 为 1 右为2)
根据index 我们计算出上一层中 父节点前面有几个节点k = index-1
则每一个节点在本层从左往右数是第几个 this= 2*k + direction
然后我们看 本层是否已经有节点被递归到了?
使用depth和全局变量list的长度比较即可
如果有的话 我们将this 与list[depth]中的最小值和最大值比 对应替换
如果还没被遍历到 即当前深度大于list长度
我们将(this,this)记录在list里面

最后 我们便利list中所有的元祖each
找到最大的each[1]-each[0]+1
返回即可

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.length = 0
        self.res = []
    def widthOfBinaryTree(self, root: TreeNode) -> int:
        if root == None:
            return 0
        if root.left == None  and  root.right == None:
            return 1
        self.res = [(1,1)]
        self.length =  1
        self.rec(root.left,1,1,1)
        self.rec(root.right,1,1,2)
        max_width = 1
        for each in self.res:
            max_width = max(max_width,each[1]-each[0] + 1)
        #print(self.res)
        return max_width
    def rec(self,root,index,depth,direction):
        if root == None:
            return None
        k = index - 1#上一层中 父节点左边有几个节点
        this = k*2 + direction#按完美二叉树计算 当前节点是这层第几个节点
        if depth > self.length-1:
            self.res.append((this,this))
            self.length += 1
        else:
            self.res[depth] = ((min(self.res[depth][0],this),max(self.res[depth][1],this)))
        self.rec(root.left,this,depth+1,1)
        self.rec(root.right,this,depth+1,2)

猜你喜欢

转载自blog.csdn.net/weixin_41545780/article/details/107577318