题目描述
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
我的解法——递归(AC)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def get_list(self, tree):
if(not tree):
return []
left = self.get_list(tree.left)
right = self.get_list(tree.right)
return left + [tree.val, ] + right
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
return self.get_list(root)
我的解法——非递归(AC)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack = []
res = []
now = root
while(now):
while(now):
stack.append(now)
now = now.left
while(len(stack) and not stack[-1].right):
res.append(stack[-1].val)
del stack[-1]
if(len(stack)):
res.append(stack[-1].val)
now = stack[-1].right
del stack[-1]
return res