中序遍历二叉树。
递归法:
# 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 __init__(self):
self.res = []
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
self.inorderTraversal(root.left)
self.res.append(root.val)
self.inorderTraversal(root.right)
return self.res
迭代法:
# 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]
"""
if not root:
return []
pNode = root
stack = []
res = []
while pNode or stack:
while pNode: #①迭代,直到找到最左的叶节点;②非空右节点
stack.append(pNode)
pNode = pNode.left
#pNode为空
pNode = stack.pop()
res.append(pNode.val)
pNode = pNode.right
return res