📜  检查二叉树是否是BST:简单有效的方法

📅  最后修改于: 2021-05-25 00:18:37             🧑  作者: Mango

给定二叉树,任务是检查给定的二叉树是否为二叉搜索树。
二进制搜索树(BST)是具有以下属性的基于节点的二进制树数据结构。

  • 节点的左子树仅包含键值小于节点键值的节点。
  • 节点的右子树仅包含键大于该节点的键的节点。
  • 左子树和右子树都必须也是二进制搜索树。

根据以上属性,自然可以得出:

  • 每个节点(树中的项目)都有一个不同的键。

BST

在上一篇文章中,我们已经讨论了解决此问题的不同方法。
在本文中,我们将讨论一种简单而有效的方法来解决上述问题。
这个想法是使用顺序遍历并跟踪先前访问的节点的值。由于BST的有序遍历会生成一个排序数组作为输出,因此,前一个元素应始终小于或等于当前元素。
在进行有序遍历时,我们可以跟踪先前访问的节点的值,如果当前访问的节点的值小于先前的值,则树不是BST。

下面是上述方法的实现:

C++
// C++ program to check if a given tree is BST.
#include 
using namespace std;
 
/* A binary tree node has data, pointer to
left child and a pointer to right child */
struct Node {
    int data;
    struct Node *left, *right;
 
    Node(int data)
    {
        this->data = data;
        left = right = NULL;
    }
};
 
// Utility function to check if Binary Tree is BST
bool isBSTUtil(struct Node* root, int& prev)
{
    // traverse the tree in inorder fashion and
    // keep track of prev node
    if (root) {
        if (!isBSTUtil(root->left, prev))
            return false;
 
        // Allows only distinct valued nodes
        if (root->data <= prev)
            return false;
 
        // Initialize prev to current
        prev = root->data;
 
        return isBSTUtil(root->right, prev);
    }
 
    return true;
}
 
// Function to check if Binary Tree is BST
bool isBST(Node* root)
{
    int prev = INT_MIN;
    return isBSTUtil(root, prev);
}
 
/* Driver code*/
int main()
{
    struct Node* root = new Node(5);
    root->left = new Node(2);
    root->right = new Node(15);
    root->left->left = new Node(1);
    root->left->right = new Node(4);
 
    if (isBST(root))
        cout << "Is BST";
    else
        cout << "Not a BST";
 
    return 0;
}


Java
// Java program to check if a given tree is BST.
class GFG {
 
    static int prev = Integer.MIN_VALUE;
    /* A binary tree node has data, pointer to
    left child and a pointer to right child */
    static class Node {
        int data;
        Node left, right;
 
        Node(int data)
        {
            this.data = data;
            left = right = null;
        }
    };
 
    // Utility function to check if Binary Tree is BST
    static boolean isBSTUtil(Node root)
    {
        // traverse the tree in inorder fashion and
        // keep track of prev node
        if (root != null) {
            if (!isBSTUtil(root.left))
                return false;
 
            // Allows only distinct valued nodes
            if (root.data <= prev)
                return false;
 
            // Initialize prev to current
            prev = root.data;
 
            return isBSTUtil(root.right);
        }
 
        return true;
    }
 
    // Function to check if Binary Tree is BST
    static boolean isBST(Node root)
    {
        return isBSTUtil(root);
    }
 
    /* Driver code*/
    public static void main(String[] args)
    {
        Node root = new Node(5);
        root.left = new Node(2);
        root.right = new Node(15);
        root.left.left = new Node(1);
        root.left.right = new Node(4);
 
        if (isBST(root))
            System.out.print("Is BST");
        else
            System.out.print("Not a BST");
    }
}
 
// This code is contributed by PrinciRaj1992


Python3
# Python3 program to check if a given tree is BST.
 
import math
prev = -math.inf
 
 
class Node:
    """
    Creates a Binary tree node that has data,
    a pointer to it's left and right child
    """
 
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data
 
 
def checkBST(root):
    """
    Function to check if Binary Tree is
    a Binary Search Tree
    :param root: current root node
    :return: Boolean value
    """
    # traverse the tree in inorder
    # fashion and update the prev node
    global prev
 
    if root:
        if not checkBST(root.left):
            return False
 
        # Handles same valued nodes
        if root.data < prev:
            return False
 
        # Set value of prev to current node
        prev = root.data
 
        return checkBST(root.right)
    return True
 
# Driver Code
def main():
    root = Node(1)
    root.left = Node(2)
    root.right = Node(15)
    root.left.left = Node(1)
    root.left.right = Node(4)
 
    if checkBST(root):
        print("Is BST")
    else:
        print("Not a BST")
 
 
if __name__ == '__main__':
    main()
 
# This code is contributed by priyankapunjabi94


C#
// C# program to check if a given tree is BST.
using System;
 
class GFG {
 
    /* A binary tree node has data, pointer to
    left child and a pointer to right child */
    class Node {
        public int data;
        public Node left, right;
 
        public Node(int data)
        {
            this.data = data;
            left = right = null;
        }
    };
 
    // Utility function to check if Binary Tree is BST
    static bool isBSTUtil(Node root, int prev)
    {
        // traverse the tree in inorder fashion and
        // keep track of prev node
        if (root != null) {
            if (!isBSTUtil(root.left, prev))
                return false;
 
            // Allows only distinct valued nodes
            if (root.data <= prev)
                return false;
 
            // Initialize prev to current
            prev = root.data;
 
            return isBSTUtil(root.right, prev);
        }
 
        return true;
    }
 
    // Function to check if Binary Tree is BST
    static bool isBST(Node root)
    {
        int prev = int.MinValue;
        return isBSTUtil(root, prev);
    }
 
    /* Driver code*/
    public static void Main(String[] args)
    {
        Node root = new Node(5);
        root.left = new Node(2);
        root.right = new Node(15);
        root.left.left = new Node(1);
        root.left.right = new Node(4);
 
        if (isBST(root))
            Console.Write("Is BST");
        else
            Console.Write("Not a BST");
    }
}
 
// This code is contributed by PrinciRaj1992


输出
Is BST

时间复杂度: O(N)
辅助空间: O(1)