-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-preorder-traversal.js
More file actions
46 lines (42 loc) · 1.01 KB
/
binary-tree-preorder-traversal.js
File metadata and controls
46 lines (42 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* 二叉树的前序遍历
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function (root) {
// 1. 递归
const result = [];
const preOrderTravelsalNode = (node) => {
if (node) {
result.push(node.val);
preOrderTravelsalNode(node.left);
preOrderTravelsalNode(node.right);
}
};
preOrderTravelsalNode(root);
return result;
// 2. 迭代
// return preOrderTraversalIterate(root);
}
function preOrderTraversalIterate(root){
const result = [];
const stack = [];
root && stack.push(root);
while (stack.length > 0) {
// 出栈
const node = stack.pop();
result.push(node.val);
// 入栈
node.right && stack.push(node.right);
node.left && stack.push(node.left);
}
return result;
};