?LeetCode刷題實(shí)戰(zhàn)255:驗(yàn)證前序遍歷序列二叉搜索樹(shù)
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
You may assume each number in the sequence is unique.
Follow up: Could you do it using only constant space complexity?
示例
示例 1:
輸入: [5,2,6,1,3]
輸出: false
示例 2:
輸入: [5,2,1,3,6]
輸出: true
進(jìn)階挑戰(zhàn):
您能否使用恒定的空間復(fù)雜度來(lái)完成此題?
解題
class Solution {
public:
bool verifyPreorder(vector<int>& preorder) {
if (!preorder.size()) return true;
stack<int> s;
s.push(preorder[0]);
int temp = -1e10;
for (int i=1;i<preorder.size();i++)
{
if (preorder[i] < temp) return false;
while(!s.empty() && preorder[i] > s.top())
{
temp=s.top();
s.pop();
}
s.push(preorder[i]);
}
return true;
}
};
LeetCode1-240題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)241:為運(yùn)算表達(dá)式設(shè)計(jì)優(yōu)先級(jí)
LeetCode刷題實(shí)戰(zhàn)242:有效的字母異位詞
LeetCode刷題實(shí)戰(zhàn)243:最短單詞距離
LeetCode刷題實(shí)戰(zhàn)244:最短單詞距離 II
LeetCode刷題實(shí)戰(zhàn)245:最短單詞距離 III
LeetCode刷題實(shí)戰(zhàn)246:中心對(duì)稱(chēng)數(shù)
LeetCode刷題實(shí)戰(zhàn)247:中心對(duì)稱(chēng)數(shù)II
LeetCode刷題實(shí)戰(zhàn)248:中心對(duì)稱(chēng)數(shù)III
LeetCode刷題實(shí)戰(zhàn)249:移位字符串分組
LeetCode刷題實(shí)戰(zhàn)250:統(tǒng)計(jì)同值子樹(shù)
LeetCode刷題實(shí)戰(zhàn)251:展開(kāi)二維向量
LeetCode刷題實(shí)戰(zhàn)252:會(huì)議室
LeetCode刷題實(shí)戰(zhàn)253:會(huì)議室II
LeetCode刷題實(shí)戰(zhàn)254:因子的組合
