2017/11/3 Leetcode 日记

 

654. Maximum Binary Tree

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.(根节点是数组中的最大值)
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.(左子树是左子数组构造出的最大子树)
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.(右子树是右子数组构造出的最大子树)

Solutions:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
13         return solver(nums, 0, nums.size() - 1);
14     }
15     
16     TreeNode* solver(vector<int>& nums, int left, int right){
17         if (left > right ) return NULL;
18         
19         int index_max = left;
20         for(int i = left;i <= right;i++){
21             if(nums[i] > nums[index_max]) index_max = i;
22         }
23         
24         TreeNode* root = new TreeNode(nums[index_max]);
25         root->left = solver(nums, left, index_max - 1);
26         root->right = solver(nums, index_max + 1, right);
27         return root;
28     }
29 };
c++

相关文章: