From 92322870fe4664dffa3dcb8e6020626376417bb3 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sun, 13 Feb 2022 21:20:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880654.=E6=9C=80?= =?UTF-8?q?=E5=A4=A7=E4=BA=8C=E5=8F=89=E6=A0=91.md=EF=BC=89=EF=BC=9A?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0typescript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0654.最大二叉树.md | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index 44c74f89..1c73354b 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -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