给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解题思路
这是一个基础问题
class Solution:
def __init__(self):
self.ret = []
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root != None:
self.ret.append(root.val)
self.preorderTraversal(root.left)
self.preorderTraversal(root.right)
return self.ret
如果我们使用给递归的方法要怎么做呢?我们实际上可以模拟栈的操作。对于这个问题,实际上在计算机中是这样处理的。我们首先将访问node1的right
、访问node1的left
和打印node.val
压入栈中。
stack : go-1-R go-1-L cout
然后弹出cout
,我们就打印了node1.val
。接着访问node1的left
,我们发现node1的left
是空,那么什么也不做。我们接着访问node1的right
,同样的对于node1.right
,我们要推入这样的三个指令go-2-R
、go-2-L
和cout
,就变成了下面这个样子。
stack : go-2-R go-2-L cout
然后弹出cout
,我们就打印了node2.val
。接着访问node2的left
,我们要推入这样的三个指令go-3-R
、go-3-L
和cout
,就变成了下面这个样子。
stack : go-2-R go-3-R go-3-L cout
然后弹出cout
,我们就打印了node3.val
。接着访问node3的left
,我们发现为空,那们我们什么都不做。接着访问node3的right
,我们发现为空,那么我们什么也不做。接着访问node2的right
,我们发现为空,我们同样什么也不做。这个时候我们发现栈为空,那么我们就结束了所有操作。我们根据上述思路,可以很容易地写出下面的代码:
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = list()
if root == None:
return result
stack = list()
stack.append(root)
while len(stack) != 0:
top = stack.pop()
if top.right != None:
stack.append(top.right)
if top.left != None:
stack.append(top.left)
result.append(top.val)
return result
注意这个问题的关键在于理清非递归写法中的栈
操作。
我将该问题的其他语言版本添加到了我的GitHub Leetcode
如有问题,希望大家指出!!!