给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
ans = []
def hxbl(root):
nonlocal ans
if not root:
return
ans.append(root.val)
hxbl(root.left)
hxbl(root.right)
hxbl(root)
return ans
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
current = root
result = []
while len(stack) != 0 or current != None:
#栈中为空并且当前节点为空的时候,说明此时已经没有可以访问的
#节点,此时跳出循环
if current != None:
result.append(current.val)
stack.append(current)
#第一次访问的时候,将节点压入栈,去访问它的左子树
current = current.left
else:
current = stack.pop()
#第二次访问的时候,将节点弹出栈,然后去访问它的右子树
current = current.right
return result