leetcode144.二叉树的前序遍历
题目
给定一个二叉树,返回它的 前序 遍历。
示例:
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
思路
- 递归法,递归法时间44ms比87.71%的提交快,代码如下:
class Solution:
def preorderTraversal(self, root):
res = []
if not root:
return res
res += [root.val]
if root.left:
res += self.preorderTraversal(root.left)
if root.right:
res += self.preorderTraversal(root.right)
return res
2.迭代法,建一个栈,把右结点(如果存在的话)压入栈,当前左结点设为当前结点,如果不存在左结点,就从栈中弹出一个结点作为当前结点。时间36ms比98.7%提交快,代码如下:
class Solution:
def preorderTraversal(self, root):
if not root:
return
res = []
stack = [root]
tmp = root
while stack:
res.append(tmp.val)
if tmp.right:
stack.append(tmp.right)
if tmp.left:
tmp = tmp.left
else:
tmp = stack.pop()
return res