*LeetCode-Verify Preorder Sequence in Binary Search Tree

build bst using traversal那些題還要再看一遍

用一個stack 每次假如還在left subtree 即num 《 stack top 就push 假如大了 就一直pop知道不再大於 然後push進去 

但是要記錄pop出來的最後一個數字 就是已經遍歷過的左子root 不能再有小於他的了 所以記錄在一個int裏面 每次數字都要和這個紀錄比較 假如出現比他小的 就false

public class Solution {
    public boolean verifyPreorder(int[] preorder) {
        Stack <Integer> stack = new Stack<Integer> ();
        if ( preorder == null || preorder.length == 0 )
            return true;
        int low = Integer.MIN_VALUE;
        for ( int num : preorder ) {
            if ( num < low )
                return false;
            while ( !stack.isEmpty() && num > stack.peek() ) {
                low = stack.pop();
            }
            stack.push ( num );
        }
        return true;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章