WEEK#3 Maximum Binary Tree

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].


class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return Construct(nums, 0, nums.size() - 1);
    }

    TreeNode* Construct(vector<int>& nums, int StartingIndex, int EndingIndex) {
        if (EndingIndex < StartingIndex || StartingIndex > EndingIndex)
            return NULL;

        //Find the maximun number in the array, say index i, and let nums[i] be the root of the tree;
        int MaxIndex = GetMaxIndex(nums, StartingIndex, EndingIndex);
        // index of the maximun number

        TreeNode* root = new TreeNode(nums[MaxIndex]);

        root->left = Construct(nums, StartingIndex, MaxIndex - 1);
        root->right = Construct(nums, MaxIndex + 1, EndingIndex);
        return root;
    }

    int GetMaxIndex(vector<int>& nums, int StartingIndex, int EndingIndex) {
        int max = nums[StartingIndex];
        int maxindex = StartingIndex;
        for (int i = StartingIndex; i <= EndingIndex; i++) {
            if (nums[i] > max) {
                max = nums[i];
                maxindex = i;
            }
        }
        return maxindex;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容