File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
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 ]
You can’t perform that action at this time.
0 commit comments