zoukankan      html  css  js  c++  java
  • 剑指offer 二叉树的层序遍历

    剑指offer 牛客网 二叉树的层序遍历

    # -*- coding: utf-8 -*-
    """
    Created on Tue Apr  9 09:33:16 2019
    
    @author: Administrator
    层序遍历:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
                1
               /  
              2    3
             /   / 
            4  5 6   7
    返回列表:[1,2,3,4,5,6,7]
    """
    
    # -*- coding:utf-8 -*-
    class TreeNode:
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    class Solution:
        #层序遍历
        def PrintFromTopToBottom(self, root):
            # write code here
            res,result = [],[]
            if root:    #非空节点,若空直接返回空
                res.append(root)    #先将头结点加入其中
                i = 0
                while True:
                    if res[i].left:     #如果左节点非空将其加入
                        res.append(res[i].left)
                    if res[i].right:    #同理,右节点非空将其加入
                        res.append(res[i].right)
                    i += 1
                    if i == len(res):   #退出条件是当遍历到列表的长度时候退出
                        break
                for i in res:   #将节点的值加入到列表返回
                    if i:   #返回非空节点的值
                        result.append(i.val)
            return result
            
    if __name__ == '__main__':
        solution = Solution()
        node_left = TreeNode(4)
        node_right = TreeNode(5)
        root_left = TreeNode(2)
        root_left.left = node_left
        root_left.right = node_right
        
        node_left = TreeNode(6)
        node_right = TreeNode(7)
        root_right = TreeNode(3)
        root_right.left = node_left
        root_right.right = node_right
        
        root = TreeNode(1)
        root.left = root_left
        root.right = root_right
    
        res = solution.PrintFromTopToBottom(root)
        print(res)
  • 相关阅读:
    行行网电子书多线程爬取
    51CTO学院IT技术课程抓取
    chromeF12 谷歌开发者工具详解 Network篇
    pyspider无法启动webui
    Python告诉你今天最冷的地方在哪里
    matplotlib画图中文及负号显示问题
    数据分析案例
    seaborn.barplot用法
    Python大数据分析之数据分析
    python中yield的用法详解
  • 原文地址:https://www.cnblogs.com/missidiot/p/10675215.html
Copyright © 2011-2022 走看看