2015-08-17 3 views
0

Я пытаюсь изучить PHP по-разному, чтобы улучшить свои навыки. Вот проблема. Есть ли способ узнать, является ли данное дерево BST (двоичный поиск дерево) или нет в PHP. Я пробовал с языком C. Может ли кто-нибудь помочь мне с PHP? Вот мой код на языке C.php реализация двоичного дерева является BST

#include <stdio.h> 
    #include <stdlib.h> 

    struct node 
    { 
    int data; 
    struct node* left; 
    struct node* right; 
}; 

static struct node *prev = NULL; 

/*Function to check whether the tree is BST or not*/ 
int is_bst(struct node* root) 
{ 
    if (root) 
    { 
     if (!is_bst(root->left)) //moves towards the leftmost child of the tree and checks for the BST 
      return 0; 
     if (prev != NULL && root->data <= prev->data) 
      return 0; 
     prev = root; 
     return is_bst(root->right); //moves the corresponding right child of the tree and checks for the BST 
    } 
    return 1; 
} 

struct node* newNode(int data) 
{ 
    struct node* node = (struct node*)malloc(sizeof(struct node)); 
    node->data = data; 
    node->left = NULL; 
    node->right = NULL; 

    return(node); 
} 

int main() 
{ 
    struct node *root = newNode(40); 
    root->left  = newNode(20); 
    root->right  = newNode(60); 
    root->left->left = newNode(10); 
    root->left->right = newNode(30); 
    root->right->right = newNode(80); 
    root->right->right->right = newNode(90); 
    if (is_bst(root)) 
     printf("TREE 1 Is BST"); 
    else 
     printf("TREE 1 Not a BST"); 
    prev = NULL; 
    return 0; 
} 

ответ

0

Вы можете по существу запустить тот же алгоритм, если ваше определение класса и экземпляр объявлены/представлены в PHP.

Как выглядит ваш PHP-код?