问题
给定一个二叉树的根节点 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)