[LeetCode]94. 二叉树的中序遍历
2018-11-26 本文已影响201人
杏仁小核桃
94. 二叉树的中序遍历
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]
二叉树的中序遍历是树的遍历中深度优先遍历的一种, 遍历方式是先左子树,后根结点,最后右子树.

解法1
递归算法
class Solution:
def inorderTraversal(self, root):
res = []
def core(root, res):
if root:
core(root.left, res)
res.append(root.val)
core(root.right, res)
core(root,res)
return res
解法2
迭代算法
class Solution(object):
def inorderTraversal(self, root):
stack=[]
res=[]
node=root
while node or len(stack)>0:
if node:
stack.append(node)
node=node.left
else:
node=stack.pop()
res.append(node.val)
node=node.right
return res