Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

이진 트리가 BST인지 확인하는 C++ 프로그램

<시간/>

이진 검색 트리는 3가지 속성이 있는 이진 트리 데이터 구조입니다 -

  • 노드의 이진 탐색 트리의 왼쪽 하위 트리에는 해당 노드의 키보다 작은 키를 가진 노드만 포함됩니다.

  • 이진 검색 트리 노드의 오른쪽 하위 트리에는 해당 노드의 키보다 큰 키를 가진 노드만 포함됩니다.

  • 하위 트리의 왼쪽과 오른쪽도 각각 이진 검색 트리여야 합니다.

알고리즘

Begin
   function BSTUtill()
      If node is equals to NULL then
         Return 1.
      If data of node is less than minimum or greater than
      maximum data then
         Return 0.
      Traverse left and right sub-trees recursively. 
End.

예시 코드

#include <iostream>
#include <cstdlib>
#include <climits>
using namespace std;
struct n {
   int d;
   n* l;
   n* r;
};
int BSTUtil(n* node, int min, int max);
int isBST(n* node) {
   return(BSTUtil(node, INT_MIN, INT_MAX));
}
int BSTUtil(struct n* node, int min, int max) {
   if (node==NULL)
      return 1;
   if (node->d < min || node->d > max)
      return 0;
      return BSTUtil(node->l, min, node->d - 1) && BSTUtil(node->r, node->d + 1, max);
}
n* newN(int d) {
   n* nod = new n;
   nod->d = d;
   nod->l = NULL;
   nod->r = NULL;
   return nod;
}
int main() {
   n *root = newN(7);
   root->l = newN(6);
   root->r = newN(10);
   root->l->l = newN(2);
   root->l->r = newN(4);
   if (isBST(root))
      cout<<"The Given Binary Tree is a BST"<<endl;
   else
      cout<<"The Given Binary Tree is not a BST"<<endl;
      n *root1 = newN(10);
      root1->l = newN(6);
      root1->r = newN(11);
      root1->l->l = newN(2);
      root1->l->r = newN(7);
      if (isBST(root1))
         cout<<"The Given Binary Tree is a BST"<<endl;
      else
         cout<<"The Given Binary Tree is not a BST"<<endl;
      return 0;
}

출력

The Given Binary Tree is not a BST
The Given Binary Tree is a BST