1. 程式人生 > 實用技巧 >leetcode255 - Verify Preorder Sequence in Binary Search Tree - medium

leetcode255 - Verify Preorder Sequence in Binary Search Tree - medium

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?

preorder是一路走到最左邊的leaf,然後每個node訪問右子樹再一路回上來,再走root的右邊。如果sequence裡的值是逐漸變小的,說明我們在向最左leaf走。直到有個值變大了那一定是訪問到某個右子樹了,而它的parent一定在之前走過的node裡。用一個stack裝所有左子樹的值,遇到比棧頂大的數x時,逐一pop stack,直到棧頂比當前這個數大,那最後一個pop出來的,也就是前一個pop出來的數就是x的parent。同時還要有一個var來track每次找到的這個parent,因為sequence裡在它之後的數都應該比它大。遍歷的時候每個數都要push進stack一遍,比如例子裡的3,它相對於之後的6,也是5的左子樹的一員。 實現: Time&Space O(n)
class
Solution { 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; } };