zoukankan      html  css  js  c++  java
  • 剑指offer60-把二叉树打印成多行**

    题目描述

    从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

    示例

    输入        {8,6,10,5,7,9,11}

    返回值    [[8],[6,10],[5,7,9,11]]

    知识点回顾:

    树、BFS

    代码

    解法一:暴力循环

    用两个列表分别保存当前层节点和下一层节点;循环添加当前层节点的左右子节点: 当前层列表,下一层列表 = 下一层列表, [] ;直到当前层为空

    # -*- coding:utf-8 -*-
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution:
        def Print(self, pRoot):
            # write code here
            if pRoot is None:
                return []
            cur_depth=[pRoot]            #当前层
            next_depth=[]                #下一层
            rlt=[]
            while cur_depth:
                for i in cur_depth:
                    if i.left:
                        next_depth.append(i.left)
                    if i.right:
                        next_depth.append(i.right)
                rlt.append([i.val for i in cur_depth])    #要存入数组的是当前层节点的值,注意用法[func(i) for i in list]
                cur_depth,next_depth=next_depth,[]
            return rlt

    解法二:用队列

  • 相关阅读:
    TcpClient
    文字识别
    halcon17.12 win7 64深度学框架搭建
    halcon多个形状模板匹配
    halcon 瓶盖定位
    halcol9点标定
    一个机械臂的正逆解
    Matlab robot-9.10(rvctools) 建模与正逆解
    16路舵机控制器USB访问
    C#二维码识别
  • 原文地址:https://www.cnblogs.com/foolangirl/p/14128429.html
Copyright © 2011-2022 走看看