二叉树的前序遍历
- https://leetcode.cn/problems/binary-tree-preorder-traversal/
描述
- 给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1
输入:root = [1,null,2,3]
输出:[1,2,3]
示例 2
输入:root = []
输出:[]
示例 3
输入:root = [1]
输出:[1]
示例 4
输入:root = [1,2]
输出:[1,2]
示例 5
输入:root = [1,null,2]
输出:[1,2]
提示
- 树中节点数目在范围 [0, 100] 内
- -100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
Typescript 算法实现
1 )方案 1
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function preorderTraversal(root: TreeNode | null): number[] {
const result: number[] = []
const isValid = (val: any) => val !== null;
const preorderHandler = (root: TreeNode | null) => {
if(!root) return result;
isValid(root.val) && result.push(root.val);
isValid(root.left) && preorderHandler(root.left);
isValid(root.right) && preorderHandler(root.right);
return result
}
return preorderHandler(root)
};
- 前序遍历的特点:
- 访问根节点
- 对根节点的左子树进行先序遍历
- 对根节点的右子树进行先序遍历
- 记忆:根左右
- 这里用到了递归来遍历树,因为是递归,所以代码写的比较简单,缺点也就是递归自身的缺点了
2 )方案 2
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function preorderTraversal(root: TreeNode | null): number[] {
const ans = <number[]>[]; // 存放最终集合
const stack = <TreeNode[]>[]; // 存放树节点集合的栈
let cur = root; // 当前节点
while(cur || stack.length) {
while(cur) {
ans.push(cur.val); // 根的值
stack.push(cur);
cur = cur.left; // 左节点
}
if(stack.length){
cur = stack.pop();
cur = cur.right; // 右节点
}
}
return ans;
};
- 这是官方示例,不用递归,用一个栈来捯饬
- 理论上,这种方案更合适
Python3 版算法实现
1 )方案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: Optional[TreeNode]) -> List[int]:
result = []
def preorderHandler(node: Optional[TreeNode]):
if not node:
return
result.append(node.val)
preorderHandler(node.left)
preorderHandler(node.right)
preorderHandler(root)
return result
2 )方案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: Optional[TreeNode]) -> List[int]:
ans = []
stack = []
cur = root
while cur or stack:
while cur:
ans.append(cur.val) # 根的值
stack.append(cur)
cur = cur.left # 左节点
if stack:
cur = stack.pop()
cur = cur.right # 右节点
return ans
Golang 版算法实现
1 )方案1 使用递归
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func preorderTraversal(root *TreeNode) []int {
var result []int
preorderHandler(root, &result)
return result
}
func preorderHandler(root *TreeNode, result *[]int) {
if root == nil {
return
}
*result = append(*result, root.Val)
preorderHandler(root.Left, result)
preorderHandler(root.Right, result)
}
2 )方案2 使用迭代
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func preorderTraversal(root *TreeNode) []int {
ans := []int{}
stack := []*TreeNode{}
cur := root
for cur != nil || len(stack) > 0 {
for cur != nil {
ans = append(ans, cur.Val) // 根的值
stack = append(stack, cur)
cur = cur.Left // 左节点
}
if len(stack) > 0 {
cur = stack[len(stack)-1]
stack = stack[:len(stack)-1]
cur = cur.Right // 右节点
}
}
return ans
}
2154



被折叠的 条评论
为什么被折叠?



