Skip to content

Commit 322a11a

Browse files
add JS solution for 0035 0098 0104
1 parent 315d9c2 commit 322a11a

File tree

3 files changed

+103
-0
lines changed

3 files changed

+103
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
var searchInsert2 = function (nums, target) {
2+
for (let i = 0; i < nums.length; i++) {
3+
if (nums[i] >= target) {
4+
return i;
5+
}
6+
}
7+
return nums.length;
8+
}
9+
10+
var searchInsert = function (nums, target) {
11+
let left = 0;
12+
let right = nums.length - 1;
13+
14+
if (target < nums[left]) {
15+
return 0;
16+
} else if (target > nums[right]) {
17+
return right + 1;
18+
}
19+
20+
let count = 0;
21+
22+
while (left < right) {
23+
if (left + 1 == right) {
24+
if (nums[left] < target) {
25+
return left + 1;
26+
} else {
27+
return left;
28+
}
29+
}
30+
31+
let mid = Math.floor((left + right) / 2);
32+
if (nums[mid] < target) {
33+
left = mid;
34+
} else if (nums[mid] > target) {
35+
right = mid;
36+
} else {
37+
return mid;
38+
}
39+
}
40+
41+
return left;
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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 {boolean}
11+
*/
12+
var isValidBST = function(root) {
13+
if (root == null) return true
14+
let arr = []
15+
inOrderTraverse(root, arr)
16+
for (let i = 0; i < arr.length - 1; i++) {
17+
if (arr[i] >= arr[i + 1]) return false
18+
}
19+
return true
20+
}
21+
22+
var inOrderTraverse = function(node, arr) {
23+
if (node !== null) {
24+
inOrderTraverse(node.left, arr)
25+
arr.push(node.val)
26+
inOrderTraverse(node.right, arr)
27+
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
var maxDepth = function(root) {
13+
if (!root) return 0
14+
let depth = 1
15+
return search(root,depth)
16+
};
17+
18+
function search(root, depth) {
19+
if (!root.left && !root.right) {
20+
return depth
21+
} else if (root.left && !root.right) {
22+
return search(root.left, depth + 1)
23+
} else if (root.right && !root.left) {
24+
return search(root.right, depth + 1)
25+
} else if (root.left && root.right) {
26+
return Math.max(search(root.left, depth+1), search(root.right,depth+1))
27+
}
28+
}
29+
30+
var maxDepth2 = function(root) {
31+
if (!root) return 0
32+
return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1
33+
}

0 commit comments

Comments
 (0)