File tree Expand file tree Collapse file tree 1 file changed +84
-0
lines changed
Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
2+ // 二叉树的中序遍历
3+ /**
4+ * 二叉树的前中后,是根据根节点的遍历位置进行控制的
5+ *左-根-右
6+ * Definition for a binary tree node.
7+ * function TreeNode(val, left, right) {
8+ * this.val = (val===undefined ? 0 : val)
9+ * this.left = (left===undefined ? null : left)
10+ * this.right = (right===undefined ? null : right)
11+ * }
12+ */
13+ /**
14+ * @param {TreeNode } root
15+ * @return {number[] }
16+ */
17+ // 1. 递归 O(n) O(n)
18+ var inorderTraversal = function ( root ) {
19+ const res = [ ] ;
20+ const inorder = ( root ) => {
21+ if ( ! root ) {
22+ return ;
23+ }
24+ inorder ( root . left ) ;
25+ res . push ( root . val ) ;
26+ inorder ( root . right ) ;
27+ } ;
28+ inorder ( root ) ;
29+ return res ;
30+ } ;
31+
32+ // 2. 迭代 O(n) O(n), 两种方式是等价的,区别在于递归的时候隐式地维护了一个栈,而我们在迭代的时候需要显式地将这个栈模拟出来,其他都相同,
33+ var inorderTraversal = function ( root ) {
34+ const res = [ ] ;
35+ const stack = [ ] ;
36+ while ( root || stack . length ) {
37+ while ( root ) {
38+ stack . push ( root ) ;
39+ root = root . left ;
40+ }
41+ root = stack . pop ( ) ;
42+ res . push ( root . val ) ;
43+ root = root . right ;
44+ }
45+ return res ;
46+ } ;
47+
48+ var inorderTraversal = function ( root ) {
49+ const stack = [ ] ;
50+ const res = [ ] ;
51+
52+ while ( root || stack . length ) {
53+ if ( root ) {
54+ stack . push ( root ) ;
55+ root = root . left ;
56+ } else {
57+ root = stack . pop ( ) ;
58+ res . push ( root . val ) ;
59+ root = root . right ;
60+ }
61+ }
62+
63+ return res ;
64+ } ;
65+
66+ // 中序遍历:左中右
67+ // 压栈顺序:右中左
68+
69+ var inorderTraversal = function ( root , res = [ ] ) {
70+ const stack = [ ] ;
71+ if ( root ) stack . push ( root ) ;
72+ while ( stack . length ) {
73+ const node = stack . pop ( ) ;
74+ if ( ! node ) {
75+ res . push ( stack . pop ( ) . val ) ;
76+ continue ;
77+ }
78+ if ( node . right ) stack . push ( node . right ) ; // 右
79+ stack . push ( node ) ; // 中
80+ stack . push ( null ) ;
81+ if ( node . left ) stack . push ( node . left ) ; // 左
82+ }
83+ return res ;
84+ } ;
You can’t perform that action at this time.
0 commit comments