给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if root is None:
return []
ans = []
stack = [(0,root)]
while stack:
flag, node = stack.pop()
if node is None:
continue
if flag == 0:
stack.append((0, node.right))
stack.append((0, node.left))
stack.append((1, node))
else:
ans.append(node.val)
return ans
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if root is None:
return []
stack = [root]
ans = []
while stack:
node = stack.pop()
ans.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return ans