实现二叉树的中序遍历
# 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 root == None:
return []
res = []
res += self.inorderTraversal(root.left)
res.append(root.val)
res += self.inorderTraversal(root.right)
return res
#非递归的方法 借助栈的方式
stack = []
p = root
res = []
while p or stack:
while p:
stack.append(p)
p = p.left
p = stack.pop()
res.append(p.val)
p = p.right
return res
网友评论