-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_solution.js
105 lines (96 loc) · 2.22 KB
/
my_solution.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
class TreeNode {
constructor(val, left, right) {
this.val = (val === undefined ? 0 : val);
this.left = (left === undefined ? null : left);
this.right = (right === undefined ? null : right);
}
}
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function (root, k) {
let list = [], kValue = null, parents = []; // stack
const inOrder = (node) => {
console.log("parents")
console.log(parents)
if (node === null || k === 0) return;
if (node.left !== null) { // going left
parents.push(node);
inOrder(node.left);
} else { // returning to right
k--;
kValue = node.val;
list.push(node.val);
if (node.right === null && parents.length > 0) {
console.log("r null")
let parent = parents.pop();
parent.left = null;
inOrder(parent);
} else {
inOrder(node.right);
}
}
}
inOrder(root);
return kValue;
};
// var kthSmallest = function (root, k) {
// let list = [], kValue = null, parents = [];
//
// const inOrder = (node) => {
// console.log("parents")
// console.log(parents)
// if (node === null || k === 0) return;
//
// if (node.left !== null) { // going left
// parents.push(node);
// inOrder(node.left);
// } else { // returning to right
// k--;
// kValue = node.val;
// list.push(node.val);
//
// if (node.right === null && parents.length > 0) {
// console.log("r null")
// let parent = parents.pop();
// parent.left = null;
// inOrder(parent);
// } else { // going to right if there is a right node otherwise we go to the the last parent
// inOrder(node.right);
// }
// }
// }
//
// inOrder(root);
//
// return kValue;
// };
let x =
// [1]
kthSmallest(
new TreeNode(1),
1
)
// // [5,3,6,2,4,null,null,1]
// kthSmallest(
// new TreeNode(
// 5,
// new TreeNode(3,
// new TreeNode(2, new TreeNode(1)),
// new TreeNode(4)),
// new TreeNode(6)
// ),
// 3
// )
// kthSmallest(
// new TreeNode(
// 3,
// new TreeNode(1, null, new TreeNode(2)),
// new TreeNode(4)
// ),
// 3
// )
console.log("x")
console.log(x)