leetcode255 - Verify Preorder Sequence in Binary Search Tree - medium
阿新 • • 發佈:2020-10-28
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.
Consider the followingbinary search tree:
5 / \ 2 6 / \ 1 3
Example 1:
Input: [5,2,6,1,3] Output: false
Example 2:
Input: [5,2,1,3,6] Output: true
Follow up:
Could you do it using only constant space complexity?
classSolution { public: bool verifyPreorder(vector<int>& preorder) { stack<int> leftSubtreeValues; int parent = INT_MIN; for (int val : preorder){ if (val < parent) return false; while (!leftSubtreeValues.empty() && leftSubtreeValues.top() < val){ parent= leftSubtreeValues.top(); leftSubtreeValues.pop(); } leftSubtreeValues.push(val); } return true; } };