Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c55bd56

Browse files
authored
Merge branch 'youngyangyang04:master' into master
2 parents caad5f9 + 5b7ed8d commit c55bd56

File tree

2 files changed

+68
-1
lines changed

2 files changed

+68
-1
lines changed

problems/0108.将有序数组转换为二叉搜索树.md

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ class Solution {
251251
return root;
252252
}
253253
}
254-
```
254+
```
255255

256256
迭代: 左闭右闭 [left,right]
257257
```java
@@ -373,7 +373,24 @@ var sortedArrayToBST = function (nums) {
373373
};
374374
```
375375

376+
## TypeScript
377+
378+
```typescript
379+
function sortedArrayToBST(nums: number[]): TreeNode | null {
380+
function recur(nums: number[], left: number, right: number): TreeNode | null {
381+
if (left > right) return null;
382+
let mid: number = Math.floor((left + right) / 2);
383+
const root: TreeNode = new TreeNode(nums[mid]);
384+
root.left = recur(nums, left, mid - 1);
385+
root.right = recur(nums, mid + 1, right);
386+
return root;
387+
}
388+
return recur(nums, 0, nums.length - 1);
389+
};
390+
```
391+
376392
## C
393+
377394
递归
378395
```c
379396
struct TreeNode* traversal(int* nums, int left, int right) {

problems/0669.修剪二叉搜索树.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,56 @@ var trimBST = function (root,low,high) {
405405
}
406406
```
407407

408+
## TypeScript
409+
410+
> 递归法
411+
412+
```typescript
413+
function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {
414+
if (root === null) return null;
415+
if (root.val < low) {
416+
return trimBST(root.right, low, high);
417+
}
418+
if (root.val > high) {
419+
return trimBST(root.left, low, high);
420+
}
421+
root.left = trimBST(root.left, low, high);
422+
root.right = trimBST(root.right, low, high);
423+
return root;
424+
};
425+
```
426+
427+
> 迭代法
428+
429+
```typescript
430+
function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {
431+
while (root !== null && (root.val < low || root.val > high)) {
432+
if (root.val < low) {
433+
root = root.right;
434+
} else if (root.val > high) {
435+
root = root.left;
436+
}
437+
}
438+
let curNode: TreeNode | null = root;
439+
while (curNode !== null) {
440+
while (curNode.left !== null && curNode.left.val < low) {
441+
curNode.left = curNode.left.right;
442+
}
443+
curNode = curNode.left;
444+
}
445+
curNode = root;
446+
while (curNode !== null) {
447+
while (curNode.right !== null && curNode.right.val > high) {
448+
curNode.right = curNode.right.left;
449+
}
450+
curNode = curNode.right;
451+
}
452+
return root;
453+
};
454+
```
455+
456+
457+
408458

409459
-----------------------
410460
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)