Class Solution

java.lang.Object
g0601_0700.s0654_maximum_binary_tree.Solution

public class Solution extends Object
654 - Maximum Binary Tree.<p>Medium</p> <p>You are given an integer array <code>nums</code> with no duplicates. A <strong>maximum binary tree</strong> can be built recursively from <code>nums</code> using the following algorithm:</p> <ol> <li>Create a root node whose value is the maximum value in <code>nums</code>.</li> <li>Recursively build the left subtree on the <strong>subarray prefix</strong> to the <strong>left</strong> of the maximum value.</li> <li>Recursively build the right subtree on the <strong>subarray suffix</strong> to the <strong>right</strong> of the maximum value.</li> </ol> <p>Return <em>the <strong>maximum binary tree</strong> built from</em> <code>nums</code>.</p> <p><strong>Example 1:</strong></p> <p><img src="https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg" alt="" /></p> <p><strong>Input:</strong> nums = [3,2,1,6,0,5]</p> <p><strong>Output:</strong> [6,3,5,null,2,0,null,null,1]</p> <p><strong>Explanation:</strong> The recursive calls are as follow:</p> <ul> <li> <p>The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].</p> <ul> <li> <p>The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].</p> <ul> <li> <p>Empty array, so no child.</p> </li> <li> <p>The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].</p> <ul> <li> <p>Empty array, so no child.</p> </li> <li> <p>Only one element, so child is a node with value 1.</p> </li> </ul> </li> </ul> </li> <li> <p>The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].</p> <ul> <li> <p>Only one element, so child is a node with value 0.</p> </li> <li> <p>Empty array, so no child.</p> </li> </ul> </li> </ul> </li> </ul> <p><strong>Example 2:</strong></p> <p><img src="https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg" alt="" /></p> <p><strong>Input:</strong> nums = [3,2,1]</p> <p><strong>Output:</strong> [3,null,2,null,1]</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= nums.length <= 1000</code></li> <li><code>0 <= nums[i] <= 1000</code></li> <li>All integers in <code>nums</code> are <strong>unique</strong>.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • constructMaximumBinaryTree

      public TreeNode constructMaximumBinaryTree(int[] nums)