二叉树遍历

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


def build_tree(n):
    nodes = [TreeNode(i) for i in range(n)]
    for i in range(n):
        l = 2*i + 1
        r = 2*i + 2
        if l < n:
            nodes[i].left = nodes[l]
        if r < n:
            nodes[i].right = nodes[r]
        if r == n:
            break
    return nodes[0]


def level(root):
    res = []
    queue = [root]
    while queue:
        cur = queue.pop(0)
        res.append(cur.val)
        if cur.left:
            queue.append(cur.left)
        if cur.right:
            queue.append(cur.right)
    return res


def level2(root):
    res = []
    l1 = [root]
    l2 = []
    while l1:
        cur = []
        for node in l1:
            cur.append(node.val)
            if node.left:
                l2.append(node.left)
            if node.right:
                l2.append(node.right)
        l1, l2 = l2, []
        res.append(cur)
    return res


def preorder2(root):
    if not root:
        return
    res = []
    def helper(root):
        nonlocal res
        if not root:
            return
        res.append(root.val)
        helper(root.left)
        helper(root.right)
    helper(root)
    return res


def preorder(root):
    if not root:
        return []
    stack = [root]
    res = []
    while stack:
        cur = stack.pop()
        res.append(cur.val)
        if cur.right:
            stack.append(cur.right)
        if cur.left:
            stack.append(cur.left)
    return res


def inorder(root):
    res = []
    stack = []
    cur = root
    while stack or cur:
        while cur:
            stack.append(cur)
            cur = cur.left
        cur = stack.pop()
        res.append(cur.val)
        cur = cur.right
    return res



def postorder(root):
    if not root:
        return []
    res = []
    stack = [root]
    while stack:
        cur = stack.pop()
        res.append(cur.val)
        if cur.left:
            stack.append(cur.left)
        if cur.right:
            stack.append(cur.right)
    return res[::-1]


if __name__ == '__main__':
    n = 7
    root = build_tree(n)
    print("层次遍历:", level(root))
    print("层次遍历2:", level2(root))
    print("前序遍历(非递归):", preorder(root))
    print("中序遍历(非递归):", inorder(root))
    print("后序遍历(非递归):", postorder(root))

输出:

层次遍历: [0, 1, 2, 3, 4, 5, 6]
层次遍历2: [[0], [1, 2], [3, 4, 5, 6]]
前序遍历(非递归): [0, 1, 3, 4, 2, 5, 6]
中序遍历(非递归): [3, 1, 4, 0, 5, 2, 6]
后序遍历(非递归): [3, 4, 1, 5, 6, 2, 0]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值