655. 输出二叉树

25 篇文章 0 订阅


655. 输出二叉树

题目描述

在这里插入图片描述

代码实现

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def printTree(self, root: TreeNode) -> List[List[str]]:
        # 设树高h, 则内层列表元素个数为2**h - 1
        def get_depth(root):
            if not root:
                return 0
            return 1 + max(get_depth(root.left), get_depth(root.right))
        
        depth = get_depth(root)
        # res = [[""] * (2**depth - 1)]* depth  ### 注意不能使用这一句,因为外层列表是复制引用,参考https://www.cnblogs.com/molinchn/p/14090035.html
        res = [[''] * (2**depth - 1) for _ in range(depth)]
        
        def pre_order(root, level=0, low=0, high=2**depth - 1 -1): # 2**depth - 1是每一层元素个数,2**depth - 1 -1是最后一个位置下标
            if not root:
                return 
            mid = low + (high - low) // 2
            res[level][mid] = str(root.val)
            pre_order(root.left, level + 1, low, mid - 1)
            pre_order(root.right, level + 1, mid + 1, high)
        
        pre_order(root)
        return res

参考

https://leetcode-cn.com/problems/print-binary-tree/solution/655-shu-chu-er-cha-shu-by-jue-qiang-zha-zha/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值