不管是前中后序遍历,有个非常简单的办法就是递归,先来用递归:
# 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]
"""
l=[]
def add(root):
if root==None:
return
add(root.left)
l.append(root.val)
add(root.right)
add(root)
return l
按照题目说的迭代来:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
l1=[]
l2=[]
p=root
while l2 or p:
while p:
l2.append(p)
p=p.left #左子树
p=l2.pop()
l1.append(p.val)
p=p.right #开始判断右子树
return l1