Skip to content

Commit

Permalink
添加(0654.最大二叉树.md):增加typescript版本
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaofei-2020 committed Feb 13, 2022
1 parent beeff54 commit 9232287
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions problems/0654.最大二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,56 @@ var constructMaximumBinaryTree = function (nums) {
};
```

## TypeScript

> 新建数组法:

```typescript
function constructMaximumBinaryTree(nums: number[]): TreeNode | null {
if (nums.length === 0) return null;
let maxIndex: number = 0;
let maxVal: number = nums[0];
for (let i = 1, length = nums.length; i < length; i++) {
if (nums[i] > maxVal) {
maxIndex = i;
maxVal = nums[i];
}
}
const rootNode: TreeNode = new TreeNode(maxVal);
rootNode.left = constructMaximumBinaryTree(nums.slice(0, maxIndex));
rootNode.right = constructMaximumBinaryTree(nums.slice(maxIndex + 1));
return rootNode;
};
```
> 使用数组索引法:
```typescript
function constructMaximumBinaryTree(nums: number[]): TreeNode | null {
// 左闭右开区间[begin, end)
function recur(nums: number[], begin: number, end: number): TreeNode | null {
if (begin === end) return null;
let maxIndex: number = begin;
let maxVal: number = nums[begin];
for (let i = begin + 1; i < end; i++) {
if (nums[i] > maxVal) {
maxIndex = i;
maxVal = nums[i];
}
}
const rootNode: TreeNode = new TreeNode(maxVal);
rootNode.left = recur(nums, begin, maxIndex);
rootNode.right = recur(nums, maxIndex + 1, end);
return rootNode;
}
return recur(nums, 0, nums.length);
};
```



## C

```c
struct TreeNode* traversal(int* nums, int left, int right) {
//若左边界大于右边界,返回NULL
Expand Down

0 comments on commit 9232287

Please sign in to comment.