From d9bac861e8f77aa1160f0af56503da9eced46f8b Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:16:51 +0800 Subject: [PATCH] =?UTF-8?q?Update=200654.=E6=9C=80=E5=A4=A7=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0654.最大二叉树 Java版本 --- problems/0654.最大二叉树.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index af133e0c..83981728 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -224,7 +224,35 @@ root->right = traversal(nums, maxValueIndex + 1, right); Java: +```Java +class Solution { + public TreeNode constructMaximumBinaryTree(int[] nums) { + return constructMaximumBinaryTree1(nums, 0, nums.length); + } + public TreeNode constructMaximumBinaryTree1(int[] nums, int leftIndex, int rightIndex) { + if (rightIndex - leftIndex < 1) {// 没有元素了 + return null; + } + if (rightIndex - leftIndex == 1) {// 只有一个元素 + return new TreeNode(nums[leftIndex]); + } + int maxIndex = leftIndex;// 最大值所在位置 + int maxVal = nums[maxIndex];// 最大值 + for (int i = leftIndex + 1; i < rightIndex; i++) { + if (nums[i] > maxVal){ + maxVal = nums[i]; + maxIndex = i; + } + } + TreeNode root = new TreeNode(maxVal); + // 根据maxIndex划分左右子树 + root.left = constructMaximumBinaryTree1(nums, leftIndex, maxIndex); + root.right = constructMaximumBinaryTree1(nums, maxIndex + 1, rightIndex); + return root; + } +} +``` Python: