实现一个二叉树的前序遍历
时间: 2023-12-01 12:03:55 浏览: 49
二叉树前序遍历的定义是:先访问根结点,然后遍历左子树,最后遍历右子树。可以通过递归或者迭代的方式实现。
递归实现:
```
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]:
result = []
self.preorder(root, result)
return result
def preorder(self, node, result):
if not node:
return
result.append(node.val)
self.preorder(node.left, result)
self.preorder(node.right, result)
```
迭代实现:
```
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
result.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
```
阅读全文