LC-二叉树的前序遍历

题目描述

二叉树的前序遍历

给定一个二叉树,返回它的 前序 遍历。

1
2
3
4
5
6
7
8
输入: [1,null,2,3]  
1
\
2
/
3

输出: [1,2,3]

代码实现

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
if (!root) {
return [];
}
let result = [];
function recursive(root) {
result.push(root.val);
root.left && recursive(root.left);
root.right && recursive(root.right);
}
recursive(root);
return result;
};

栈 + 迭代

在前序后序和中序遍历中,这个的迭代方法应该是最好写的了。

这里注意要运用栈的原理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function (root) {
if (!root) return [];
let result = [];
let stack = [root];
while (stack.length) {
let node = stack.pop();
result.push(node.val);
node.right && stack.push(node.right);
node.left && stack.push(node.left);
}
return result;
};