Skip to content

Commit ef2c16b

Browse files
author
liuxiangyang
committed
144. 二叉树的前序遍历
1 parent 467b8b4 commit ef2c16b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

144. 二叉树的前序遍历.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {number[]}
11+
*/
12+
// 递归
13+
var preorderTraversal = function (root) {
14+
let result = []
15+
let preorderTraversalNode = node => {
16+
if (node) {
17+
result.push(node.val)
18+
preorderTraversalNode(node.left)
19+
preorderTraversalNode(node.right)
20+
}
21+
}
22+
preorderTraversalNode(root)
23+
return result
24+
};
25+
26+
// 递归(es6优化版本) 时间98% 空间100%
27+
var preorderTraversal = function (root) {
28+
return root ?
29+
[root.val, ...preorderTraversal(root.left),
30+
...preorderTraversal(root.right)]
31+
: []
32+
};
33+
34+
// 迭代
35+
var preorderTraversal = function (root) {
36+
let result = [], stack = [], cur
37+
if (root) stack.push(root)
38+
while (stack.length > 0) {
39+
cur = stack.pop()
40+
result.push(cur.val)
41+
cur.right !== null && stack.push(cur.right)
42+
cur.left !== null && stack.push(cur.left)
43+
}
44+
return result
45+
};
46+
47+
var root = [1, null, 2, 3]

0 commit comments

Comments
 (0)