码迷,mamicode.com
首页 > 编程语言 > 详细

python 实现二叉树相关算法

时间:2017-12-13 17:26:39      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:str   构建   实现   while   bsp   strong   new   post   算法   

一、构建与遍历二叉树

 

class Node(object):
    def __init__(self,item):
        self.key=item
        self.left=None
        self.right=None

 

class BinaryTree(object):
    def __init__(self):
        self.root=None

    def addNode(self,item):
        new_node = Node(item)
        if self.root is None:
           self.root=new_node
        else:
            stack=[]
            stack.append(self.root)
            while True:
                node=stack.pop(0)
                if node.left is None:
                    node.left=new_node
                    return
                elif node.right is None:
                    node.right=new_node
                    return
                else:
                    stack.append(node.left)
                    stack.append(node.right)

    def traverse(self):  #层次遍历
        if self.root is None:
            return None
        else:
            s=[]
            s.append(self.root)
            while len(s) > 0:
                node = s.pop(0)
                print(node.key)
                if node.left is not None:
                    s.append(node.left)
                if node.right is not None:
                    s.append(node.right)

    def preOrder(self,root):
        if root is None:
            return None
        print(root.key)
        self.preOrder(root.left)
        self.preOrder(root.right)

    def inOrder(self,root):
        if root is None:
            return None

        self.inOrder(root.left)
        print(root.key)
        self.inOrder(root.right)

    def postOrder(self,root):
        if root is None:
            return None

        self.postOrder(root.left)
        self.postOrder(root.right)
        print(root.key)

 

python 实现二叉树相关算法

标签:str   构建   实现   while   bsp   strong   new   post   算法   

原文地址:http://www.cnblogs.com/gczr/p/8033104.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!