LeetCode 654. Maximum Binary Tree

来源:互联网 发布:淘宝首页在线制作 编辑:程序博客网 时间:2024/06/06 02:03

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:

  6/   \3     5\    /  2  0      \    1

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

题目的意思是给定一个非序列,用此序列建树,其中根结点的值为序列中最大的数,最大数的左侧为左子树节点,右侧为右子树节点。
考察递归。

/** * 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:    int find_max_idx(vector<int>& nums, int start, int end)    {        if(start==end)            return -1;        int max_index=start;        for(int i=start;i<end;++i)        {            max_index = nums[max_index] > nums[i]?max_index:i;        }        return max_index;    }    TreeNode* buildTree(vector<int>& nums, int start, int end)    {        TreeNode *root=nullptr;        int father = find_max_idx(nums,start,end);        if(father==-1) return nullptr;        root = new TreeNode(nums[father]);            root->left = buildTree(nums, start, father);        root->right = buildTree(nums, father+1, end);        return root;    }    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {        return buildTree(nums,0,nums.size());    }};
原创粉丝点击