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;
        }
    };
  • 相关阅读:
    POJ Problem 2631 Roads in the North【树的直径】
    POJ Problem 1985 Cow Marathon 【树的直径】
    Light OJ 1049 Farthest Nodes in a Tree【树的直径】
    HDU Problem 4707 Pet【并查集】
    HDU Problem 1325 Is It A Tree?【并查集】
    HDU Problem 5631 Rikka with Graph【并查集】
    HDU Problem 5326 Work 【并查集】
    文件比较软件修改比较文件时间戳方法
    什么是Oracle 数据泵
    文件对比工具文件上传 FTP如何匹配本地文件
  • 原文地址:https://www.cnblogs.com/silentteller/p/10909388.html
Copyright © 2011-2022 走看看