美文网首页
WEEK#3 Maximum Binary Tree

WEEK#3 Maximum Binary Tree

作者: DarkKnightRedoc | 来源:发表于2017-10-22 11:32 被阅读0次

    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;
        }
    };
    

    相关文章

      网友评论

          本文标题:WEEK#3 Maximum Binary Tree

          本文链接:https://www.haomeiwen.com/subject/uveguxtx.html