zoukankan      html  css  js  c++  java
  • LeetCode 654. Maximum Binary Tree最大二叉树 (C++)

    题目:

    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. 左子树是通过数组中最大值左边部分构造出的最大二叉树。
    3. 右子树是通过数组中最大值右边部分构造出的最大二叉树。

    通过给定的数组构建最大二叉树,并且输出这个树的根节点。

    每次选出数组中的最大值作为根节点,左子树就递归执行最大值的左侧,右子树递归执行最大值的右侧。当数组为空的时候返回空指针。

    程序:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
            if(nums.size() == 0) return nullptr;
            auto it = max_element(nums.begin(), nums.end());
            TreeNode* root = new TreeNode(*it);
            vector<int> l(nums.begin(), it); 
            vector<int> r(it+1, nums.end());
            root->left = constructMaximumBinaryTree(l);
            root->right = constructMaximumBinaryTree(r);
            return root;
        }
    };
  • 相关阅读:
    AndroidWear开发之下载SDK[Android W/Android L]
    Androidの共享登录之方案研究
    AndroidのUI体验之ImmersiveMode沉浸模式
    谷歌Volley网络框架讲解——HttpStack及其实现类
    谷歌Volley网络框架讲解——网络枢纽
    05-使用jQuery操作input的values
    02-jQuery的选择器
    01-jQuery的介绍
    07-BOM client offset scroll 的系列
    06-js中的中的面向对象 定时器
  • 原文地址:https://www.cnblogs.com/silentteller/p/10909388.html
Copyright © 2011-2022 走看看