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 };
  • 相关阅读:
    Phantomjs 一些简单实用
    JAVA中关于数组的定义
    itextpdf JAVA 输出PDF文档
    MyBatis在insert插入操作时返回主键ID的配置
    卫士通加密机 控制台终端管理程序
    通过DOS、SHELL批处理命令加载Lib并编译和打包Java项目(或者运行项目)
    HTML单选按钮样式更换
    JAVA生成图片缩略图、JAVA截取图片局部内容
    JAVA笔记 之 Thread线程
    JAVA笔记 之 JDK新特性
  • 原文地址:https://www.cnblogs.com/gsz-/p/9382394.html
Copyright © 2011-2022 走看看