zoukankan      html  css  js  c++  java
  • 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.

    Construct the maximum tree by the given array and output the root node of this tree.

    Example 1:

    Input: [3,2,1,6,0,5]
    Output: return the tree root node representing the following tree:
    
          6
        /   
       3     5
            / 
         2  0   
           
            1
    

    Note:

    1. The size of the given array will be in the range [1,1000].

    解题思路:

    树的定义是递归的,一般构造方法也使用递归方法。

    代码:

     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         if (nums.size() == 0) return NULL;
    14         if (nums.size() == 1) { 
    15             TreeNode* node = new TreeNode(nums[0]);
    16             return node;
    17         }
    18         int index = findMax(nums);
    19         TreeNode* node = new TreeNode(nums[index]);
    20         vector<int> left;
    21         vector<int> right;
    22         for(int i = 0; i < index; ++i) {
    23             left.push_back(nums[i]);
    24         }
    25         for(int i = index + 1; i < nums.size(); ++i) {
    26             right.push_back(nums[i]);
    27         }
    28         node->left = constructMaximumBinaryTree(left);
    29         node->right = constructMaximumBinaryTree(right);
    30         return node;
    31     }
    32     int findMax(const vector<int>& nums) {
    33         if (nums.size() == 0) 
    34             return -1;
    35         int index = 0;
    36         int max = nums[0];
    37         for (int i = 0; i < nums.size(); ++i) {
    38             if (nums[i] > max) {
    39                 max = nums[i];
    40                 index = i;
    41             }    
    42         }
    43         return index;
    44     }
    45 };
  • 相关阅读:
    阿里云ECS安装sqlserver,本地无法连接问题排查思路
    1433端口无法连接(sql server 数据库无法访问问题)解决思路
    开源框架 电商参考系统
    版本控制工具 Git 只下载开源项目的某个文件夹
    VUE 在idea中的运行项目
    开源框架 Java Guns 03 数据库替换为sqlite
    SQL Server 用ip地址登录 127.0.0.1
    开源框架 UI框架
    电商 电商系统汇总
    电商 平台汇总
  • 原文地址:https://www.cnblogs.com/gsz-/p/9382394.html
Copyright © 2011-2022 走看看