LeetCode#654 Maximum Binary Tree (week12)

来源:互联网 发布:淘宝店已下架什么意思 编辑:程序博客网 时间:2024/05/18 01:33

week12

题目

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

The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
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:

这里写图片描述
原题地址:https://leetcode.com/problems/maximum-binary-tree/description/

解析

题目要求将给定数组中的最大元素作为二叉树的根节点,其中左子树由该最大元素左边的元素构成,右子树由该最大元素右边的元素构成,左子树的根节点为该子树中的最大元素,以此类推。
大致思路为对于给定数组,选出其最大元素作为根节点,将最大元素左边的元素和右边的元素分别构造成新的数组,对这两个数组递归使用上述过程。

代码

class Solution {public:    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {        if (nums.size() == 0) {            return NULL;        }        TreeNode *root = new TreeNode(0);        constructTree(nums, root);        return root;    }    void constructTree(vector<int>& nums, TreeNode *root) {        int index, largest;        findMax(nums, index, largest);        /* 将当前数组中最大的元素作为根节点 */        root->val = largest;        vector<int> leftTree;        vector<int> rightTree;        /* 递归调用,用最大元素左边的元素构造左子树 */        for (int i = 0; i < index; ++i) {            leftTree.push_back(nums[i]);        }        if (leftTree.size() > 0) {            root->left = new TreeNode(0);            constructTree(leftTree, root->left);        }        /* 递归调用,用最大元素右边的元素构造右子树 */        for (int i = index + 1; i < nums.size(); ++i) {            rightTree.push_back(nums[i]);        }        if (rightTree.size() > 0) {            root->right = new TreeNode(0);            constructTree(rightTree, root->right);        }    }    /* 找到当前数组中的最大元素 */    void findMax(vector<int>& nums, int &index, int &largest) {        if (nums.size() != 0) {            int tmp = nums[0];            index = 0;            for (int i = 0; i < nums.size(); ++i) {                if (nums[i] > tmp) {                    tmp = nums[i];                    index = i;                }            }            largest = tmp;        }    }};