问题描述
Given a binary tree, return the inorder traversal of its nodes' values.
Follow up: Recursive solution is trivial, could you do it iteratively?
给定一个二叉树,返回其节点值的顺序遍历。
后续工作:递归解决方案很简单,可以迭代地解决吗?
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
Python 实现
实现一:递归。由于递归调用对内存的使用较多,容易造成栈溢出,实际应用中不建议使用。
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
# Recursively.
ret = []
if root == None:
return []
if root.left != None:
ret += self.inorderTraversal(root.left)
ret.append(root.val)
if root.right != None:
ret += self.inorderTraversal(root.right)
return ret
实现二:迭代。这里使用栈的数据结构来实现,实际上实现的也是一个DFS的过程,将子树的根节点入栈,遍历至左子树根节点为空时,出栈返回上一个根节点,再从右子树根节点重复上述操作即可。
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
# Iteratively.
stack, ret, cur = [], [], root
while True:
if cur != None:
# Push the middle root node.
stack.append(cur)
cur = cur.left
elif len(stack) > 0:
# Pop the middle root node and record its value.
cur = stack.pop()
ret.append(cur.val)
cur = cur.right
else:
break
return ret
链接:https://leetcode.com/problems/binary-tree-inorder-traversal/