深色模式
BM23 二叉树的前序遍历
1. 递归法
ts
function preOrder(root: TreeNode, list: number[]): void {
if(!root) return;
list.push(root.val);
if(root.left) preOrder(root.left, list);
if(root.right) preOrder(root.right, list)
}
export function preorderTraversal(root: TreeNode): number[] {
// write code here
if(!root) return [];
var list: number[] = [];
preOrder(root, list)
return list;
}
2. 堆栈法
说明: 1. 树顶节点入栈
- 如果栈顶非空,出栈节点node, 访问当前节点
- 如果有右孩子节点,右孩子节点入栈
- 如果有左孩子节点,左孩子节点入栈
- 重复2-4步骤
ts
/*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)
* }
* }
**/
/*
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
**/
export function preorderTraversal(root: TreeNode): number[] {
// write code here
var res = []
var stack: TreeNode[] = [];
if(!root) return res;
stack.push(root)
while(stack.length) {
let node = stack.pop();
res.push(node.val);
if(node.left) stack.push(node.left);
if(node.right) stack.push(node.right);
}
return res;
}