其他分享
首页 > 其他分享> > Hackerrank Day 23: BST Level-Order Traversal 逐层遍历

Hackerrank Day 23: BST Level-Order Traversal 逐层遍历

作者:互联网

CODE

import sys

class Node:
    def __init__(self,data):
        self.right=self.left=None
        self.data = data
class Solution:
    def insert(self,root,data):
        if root==None:
            return Node(data)
        else:
            if data<=root.data:
                cur=self.insert(root.left,data)
                root.left=cur
            else:
                cur=self.insert(root.right,data)
                root.right=cur
        return root

    def levelOrder(self,root):
        #Write your code here
        nodes=[]#将节点存在list中
        results=''
        if root.data is not None:
            nodes.append(root)
        while nodes:
            tmp=nodes[0]
            results=results+str(tmp.data)+' '
            #print(str(tmp.data)+' ',end='')
            if tmp.left is not None:
                nodes.append(tmp.left)
            if tmp.right is not None:
                nodes.append(tmp.right)
            nodes.pop(0)#将对已经展开并存入result中的节点删除
        print(results)
T=int(input())
myTree=Solution()
root=None
for i in range(T):
    data=int(input())
    root=myTree.insert(root,data)
myTree.levelOrder(root)

 

weixin_45405128 发布了121 篇原创文章 · 获赞 90 · 访问量 4019 私信 关注

标签:__,Node,None,Hackerrank,Level,BST,self,data,class
来源: https://blog.csdn.net/weixin_45405128/article/details/103934697