leetcode 654. Maximum Binary Tree

1.題目

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
給一個不含重複元素的整型數組。要求構造一棵二叉樹,規則爲:
1)根結點是數組中最大的元素
2)最大元素左側的元素構成左子樹,右側的元素構成右子樹
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

2.分析

1.遞歸

用遞歸求解比較容易理解。
找出數組中最大值,作爲根結點
根結點的左子節點爲左側最大值,右子節點爲右側最大值。遞歸求解即可。

2.棧

這個數組對應唯一的一棵樹,數組中的元素其實是樹的中序遍歷。通過棧和根結點的特點可以將這棵樹還原出來。

stack s 存儲樹節點
cur 遍歷的當前元素

遍歷數組:
當s不爲空 且 棧頂節點值小於當前節點值
cur->left = s.top()->left

如果棧頂節點大於當前節點值,則
s.top()->right = cur

當前節點入棧

最終,棧底元素爲樹的根結點

3.代碼

遞歸

TreeNode* constructMaximumBinaryTree3(vector<int>& nums) {
    return buildTree(nums, 0, nums.size() - 1);
}
TreeNode* buildTree(vector<int>& nums, int left, int right) {
    if (left < right)
        return NULL;
    int idx = left;
    for (int i = left; i <= right; i++)
        idx = nums[i] > nums[idx] ? i : idx;
    TreeNode* root = new TreeNode(nums[idx]);
    root->left = buildTree(nums, left, idx - 1);
    root->right = buildTree(nums, idx + 1, right);
    return root;
}

class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        stack<TreeNode*> s;
        for (int i = 0; i < nums.size(); i++) {
            TreeNode* cur = new TreeNode(nums[i]);
            while (!s.empty() && s.top()->val < nums[i]) {
                cur->left = s.top();
                s.pop();
            }
            if (!s.empty())
                s.top()->right = cur;
            s.push(cur);
        }
        TreeNode* root;
        while(!s.empty()){
            root = s.top();
            s.pop();
        }
        return root;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章