Leetcode654. 用栈构建最大值二叉树

Leetcode654. 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:
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
6
/ \
3 5
\ /
2 0
\
1

解题分析

通过上面的例子,我们可以大概知道题目的要求:输入一个数组,如果一个元素比上一个元素小,那么就作为上一个元素的右子节点;否则,就将上一个元素作为该元素的左子节点。由此,我们可以找到对应如下的算法。

我们用栈来存储节点,并且保证栈中的元素是递减排列的。若一个元素小于栈顶元素,则将其作为栈顶元素的右子节点;如果有一个元素大于栈顶元素,就将其pop并将其作为该元素的左子节点,直到栈中元素递减排列。这样,就始终保证栈底元素是最大值对应的节点,最后只需把所有节点pop、最后一个节点就是所要返回的根元素,问题就解决了。

源代码

/**
 * 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:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        int i, size = nums.size();
        stack<TreeNode*> stack;
        TreeNode* top;
        for (i = 0; i < size; i++) {
            TreeNode* node = new TreeNode(nums[i]);
            while (!stack.empty() && stack.top()->val < nums[i]) {
                node->left = stack.top();
                stack.pop();
            }
            if (!stack.empty()) {
                stack.top()->right = node;
            }
            stack.push(node);
        }
        while (!stack.empty()) {
            top = stack.top();
            stack.pop();
        }
        return top;
    }
};

以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值