二叉树的中序遍历_CodingPark编程公园

问题

给定一个二叉树的根节点 root ,返回它的 中序 遍历。

示例 1:
在这里插入图片描述
输入:root = [1,null,2,3]
输出:[1,3,2]


示例 2:
输入:root = []
输出:[]


示例 3:
输入:root = [1]
输出:[1]


示例 4:
在这里插入图片描述
输入:root = [1,2]
输出:[2,1]


示例 5:
在这里插入图片描述
输入:root = [1,null,2]
输出:[1,2]

解答

在这里插入图片描述

# -*- encoding: utf-8 -*-
"""
@File    :   ecszx.py    
@Contact :   ag@team-ag.club
@License :   (C)Copyright 2019-2020, CodingPark

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2020/12/1 下午3:30   AG         1.0         None
"""
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

rootMINE = TreeNode(1, 'null', TreeNode(2, TreeNode(3)))
root = TreeNode(1, None, TreeNode(2, TreeNode(3)))


'''

MINE

'''
def inorderTraversal(root):
    li = []
    liRefresh = []
    while True:
        li.append(root.val)
        li.append(root.left)
        li.append(root.right)
        for i in li:
            if type(i) != int and i != 'null' and i != None:
                # print(f'{i}  =>  类')
                li.append(i.val)
                li.append(i.left)
                li.append(i.right)
        break

    for i in li:
        if type(i) == int or i == 'null':
            liRefresh.append(i)
    # print(liRefresh)
    x = []
    res = []
    if not liRefresh:
        return []
    if len(liRefresh) == 1:
        return liRefresh

    else:
        for j in liRefresh:
            if j != 'null':
                x.append(j)
            if j == 'null':
                res.append(x.pop())
        while len(x):
            res.append(x.pop())

        return res
'''

Official

'''
#
# def inorderTraversal(root: TreeNode):
#     WHITE, GRAY = 0, 1
#     res = []
#     stack = [(WHITE, root)]
#     while stack:
#         color, node = stack.pop()
#         if node is None:
#             continue
#         if color == WHITE:
#             stack.append((WHITE, node.right))
#             stack.append((GRAY, node))
#             stack.append((WHITE, node.left))
#         else:
#             res.append(node.val)
#     return res



print()
fin = inorderTraversal(rootMINE)
print('------- 程序结果 -------')
print()
print(fin)



在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TEAM-AG

编程公园:输出是最好的学习方式

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值