python 二叉树

class Node:
    def __init__(self, val=None, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Tree:
    def __init__(self, node=None):
        self.root = node

    def add(self, item=None):
        node = Node(val=item)
        if not self.root or self.root.val is None:
            self.root = node
        else:
            queue = []
            queue.append(self.root)
            while True:
                current_node = queue.pop(0)
                if current_node.val is None:
                    continue
                if not current_node.left:
                    current_node.left = node
                    return
                elif not current_node.right:
                    current_node.right = node
                    return
                else:
                    queue.append(current_node.left)
                    queue.append(current_node.right)

    def fontTranverse(self, node, tranverseList=[]):

        if node is None:
            return tranverseList
        else:
            tranverseList.append(node.val)
            if node.left is not None:
                tranverseList = self.fontTranverse(node.left, tranverseList)
            if node.right is not None:
                tranverseList = self.fontTranverse(node.right, tranverseList)
        return tranverseList

    def midTranverse(self, node, tranverseList=[]):
        if node is None:
            return tranverseList
        else:
            if node.left is None:
                tranverseList.append(node.val)
            else:
                tranverseList = self.midTranverse(node.left, tranverseList)
                tranverseList.append(node.val)
            if node.right is not None:
                tranverseList = self.midTranverse(node.right, tranverseList)
            return tranverseList

    def backTranverse(self, node, tranverseList=[]):
        if node is None:
            return tranverseList
        else:
            if node.left is None:
                tranverseList.append(node.val)
                return tranverseList
            else:
                tranverseList = self.backTranverse(node.left, tranverseList)
            if node.right is not None:
                tranverseList = self.backTranverse(node.right, tranverseList)
            tranverseList.append(node.val)
            return tranverseList




tree = Tree()
for i in range(10):
    if i == 3:
        i = None
    tree.add(i)

print(tree.fontTranverse(tree.root))
print(tree.midTranverse(tree.root))
print(tree.backTranverse(tree.root))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值