给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
进阶:递归算法很简单,你可以通过迭代算法完成吗?
Python:
1.递归:
# 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]:
res = []
def preOrder(root):
if not root:
return
else:
res.append(root.val)
preOrder(root.left)
preOrder(root.right)
preOrder(root)
return res
2.非递归
# 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]:
res = []
q = root
queue = []
while q or queue:
if q:
res.append(q.val)
queue.append(q)
q = q.left
else:
temp = queue.pop()
if temp.right:
q = temp.right
return res
留言