File tree 1 file changed +59
-0
lines changed
1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=94 lang=javascript
3
+ *
4
+ * [94] 二叉树的中序遍历
5
+ */
6
+
7
+ // @lc code=start
8
+ /**
9
+ * Definition for a binary tree node.
10
+ * function TreeNode(val, left, right) {
11
+ * this.val = (val===undefined ? 0 : val)
12
+ * this.left = (left===undefined ? null : left)
13
+ * this.right = (right===undefined ? null : right)
14
+ * }
15
+ */
16
+ /**
17
+ * @param {TreeNode } root
18
+ * @return {number[] }
19
+ */
20
+ var inorderTraversal = function ( root ) {
21
+ const result = [ ] ;
22
+ const inOrder = ( node ) => {
23
+ if ( node ) {
24
+ inOrder ( node . left ) ;
25
+ result . push ( node . val ) ;
26
+ inOrder ( node . right ) ;
27
+ }
28
+ }
29
+ // inOrder(root);
30
+
31
+ // return result;
32
+
33
+ return inOrderIterate ( root ) ;
34
+ } ;
35
+
36
+ // 中序遍历
37
+ // 左中右
38
+ function inOrderIterate ( root ) {
39
+ const result = [ ] ;
40
+ const stack = [ ] ;
41
+ let curr = root ;
42
+
43
+ while ( stack . length || curr ) {
44
+ while ( curr ) {
45
+ stack . push ( curr ) ;
46
+ curr = curr . left ;
47
+ }
48
+ const node = stack . pop ( ) ;
49
+ result . push ( node . val ) ;
50
+
51
+ if ( node . right ) {
52
+ curr = node . right ;
53
+ }
54
+ }
55
+
56
+ return result ;
57
+ }
58
+ // @lc code=end
59
+
You can’t perform that action at this time.
0 commit comments