[LeetCode]654. Maximum Binary Tree

[LeetCode]654. Maximum Binary Tree

题目描述

[LeetCode]654. Maximum Binary Tree_第1张图片

思路

参考了答案写法,用了栈
若栈不为空,若栈顶元素小于当前值,贼一直更新当前值的左子节点,直至栈空或者栈顶元素不小于当前值
之后,若栈不为空,栈顶元素右子节点为当前节点
当前节点入栈
知道遍历数组结束

代码

#include 
#include 

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {};
};

class Solution {
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        if (nums.size() == 0)
            return NULL;
        vector stk;
        for (int i = 0; i < nums.size(); ++i) {
            TreeNode* cur = new TreeNode(nums[i]);
            while (stk.size() && stk.back()->val < cur->val) {
                cur->left = stk.back();
                stk.pop_back();
            }
            if (stk.size()) {
                stk.back()->right = cur;
            }
            stk.push_back(cur);
        }
        return stk.front();
    }
};

你可能感兴趣的:(leetcode)