【算法】驗證二叉搜索樹


驗證二叉搜索樹

描述

給定一個二叉樹,判斷其是否是一個有效的二叉搜索樹。
假設一個二叉搜索樹具有如下特征:
節點的左子樹只包含小于當前節點的數。
節點的右子樹只包含大于當前節點的數。
所有左子樹和右子樹自身必須也是二叉搜索樹。

解題思路

1.中序遍歷數,結果必然是升序。
//用于記錄前一個值
    private Integer last;
    //中序遍歷樹,比較值。時間復雜度:O(n),空間復雜度:O(n)。
    public boolean isValidBST(TreeNode root) 
    {
        if (root == null) return true;
        
        if (!isValidBST(root.left)) return false;
        
        if (last != null && root.val <= last) return false;
        last = root.val;
        
        if (!isValidBST(root.right)) return false;
        
        return true;
    }
2.遍歷樹的同時指定上下限范圍,每個節點取值范圍是上下界,左節點的上界值是父節點,右節點的下界值是父節點。適合所有遍歷方式。
//層序遍歷樹,上下界比較值。時間復雜度:O(n),空間復雜度:O(n)。
    public boolean isValidBST3(TreeNode root) 
    {
        if (root == null) return true;
                
        Queue<TreeNode> nodes = new LinkedList<>();
        Queue<Integer> mins = new LinkedList<>();
        Queue<Integer> maxs = new LinkedList<>();
        
        nodes.offer(root);
        mins.offer(null);
        maxs.offer(null);
        
        while (!nodes.isEmpty()) {
            TreeNode node = nodes.poll();
            Integer min = mins.poll();
            Integer max = maxs.poll();
            
            if (min != null && node.val <= min) return false;
            if (max != null && node.val >= max) return false;
            
            if (node.left != null) {
                nodes.offer(node.left);
                mins.offer(min);
                maxs.offer(node.val);
            }
            
            if (node.right != null) {
                nodes.offer(node.right);
                mins.offer(node.val);
                maxs.offer(max);
            }
        }
        
        return true;
    }

Objective-C版:

OC版的解法

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容