Come si fa a convalidare un albero binario di ricerca?

voti
54

Ho letto su qui di un esercizio di interviste noto come la convalida di un albero binario di ricerca.

Come funziona esattamente? Che cosa sarebbe un essere alla ricerca di convalida di un albero binario di ricerca? Ho scritto un albero di ricerca di base, ma mai sentito parlare di questo concetto.

È pubblicato 01/02/2009 alle 02:41
fonte dall'utente
In altre lingue...                            


30 risposte

voti
13

"Convalida" un albero binario di ricerca significa che verificare che effettivamente ha tutti gli elementi più piccoli sulle voci di sinistra e di grandi dimensioni sulla destra. In sostanza, si tratta di un controllo per vedere se un albero binario è un binario di ricerca albero.

Risposto il 01/02/2009 a 02:44
fonte dall'utente

voti
106

In realtà questa è l'ognuno errore fa in un'intervista.

Leftchild deve essere controllata con (nodo minLimitof, node.value)

Rightchild deve essere confrontato (node.value, MAXLIMIT di nodo)

IsValidBST(root,-infinity,infinity);

bool IsValidBST(BinaryNode node, int MIN, int MAX) 
{
     if(node == null)
         return true;
     if(node.element > MIN 
         && node.element < MAX
         && IsValidBST(node.left,MIN,node.element)
         && IsValidBST(node.right,node.element,MAX))
         return true;
     else 
         return false;
}

Un'altra soluzione (se lo spazio non è un vincolo): Fare un attraversamento in ordine simmetrico dell'albero e memorizzare i valori dei nodi in una matrice. Se l'array è in modo ordinato, è un BST valida altrimenti no.

Risposto il 17/04/2009 a 11:11
fonte dall'utente

voti
5

Ecco la mia soluzione in Clojure:

(defstruct BST :val :left :right)

(defn in-order [bst]
  (when-let [{:keys [val, left, right]} bst]
    (lazy-seq
      (concat (in-order left) (list val) (in-order right)))))

(defn is-strictly-sorted? [col]
  (every?
    (fn `a b` (< a  b))
    (partition 2 1 col)))

(defn is-valid-BST [bst]
  (is-strictly-sorted? (in-order bst)))
Risposto il 08/01/2010 a 08:30
fonte dall'utente

voti
1

"E 'meglio definire un invariante primo Ecco l'invariante è -. Due elementi qualsiasi sequenziali della BST nella attraversamento in ordine devono essere in stretto ordine crescente del loro aspetto (non può essere uguale, sempre in aumento in in-order attraversamento). Quindi, la soluzione può essere solo un semplice attraversamento in ordine con ricordando l'ultimo nodo visitato e confronto il nodo corrente contro l'ultimo visitato uno a '<' (o '>')."

Risposto il 30/03/2010 a 09:07
fonte dall'utente

voti
7

soluzione iterativa con ordine simmetrico.

bool is_bst(Node *root) {
  if (!root)
    return true;

  std::stack<Node*> stack;
  bool started = false;
  Node *node = root;
  int prev_val;

  while(true) {
    if (node) {
      stack.push(node);
      node = node->left();
      continue;
    }
    if (stack.empty())
      break;
    node = stack.top();
    stack.pop();

    /* beginning of bst check */
    if(!started) {
      prev_val = node->val();
      started = true;
    } else {
      if (prev_val > node->val())
        return false;
      prev_val = node->val();
    }
    /* end of bst check */

    node = node->right();
  }
  return true;
}
Risposto il 29/04/2011 a 22:35
fonte dall'utente

voti
0

soluzione ricorsiva:

isBinary(root)
    {
        if root == null 
          return true
       else if( root.left == NULL and root.right == NULL)
          return true
       else if(root.left == NULL)
           if(root.right.element > root.element)
               rerturn isBInary(root.right)
        else if (root.left.element < root.element)
              return isBinary(root.left)
        else
              return isBInary(root.left) and isBinary(root.right)

    }
Risposto il 05/09/2011 a 16:36
fonte dall'utente

voti
1
bool BinarySearchTree::validate() {
    int minVal = -1;
    int maxVal = -1;
    return ValidateImpl(root, minVal, maxVal);
}

bool BinarySearchTree::ValidateImpl(Node *currRoot, int &minVal, int &maxVal)
{
    int leftMin = -1;
    int leftMax = -1;
    int rightMin = -1;
    int rightMax = -1;

    if (currRoot == NULL) return true;

    if (currRoot->left) {
        if (currRoot->left->value < currRoot->value) {
            if (!ValidateImpl(currRoot->left, leftMin, leftMax)) return false;
            if (leftMax != currRoot->left->value && currRoot->value < leftMax)  return false;
        }
        else
            return false;
    } else {
        leftMin = leftMax = currRoot->value;
    }

    if (currRoot->right) {
        if (currRoot->right->value > currRoot->value) {
            if(!ValidateImpl(currRoot->right, rightMin, rightMax)) return false;
            if (rightMin != currRoot->right->value && currRoot->value > rightMin)  return false;
        }
        else return false;
    } else {
        rightMin = rightMax = currRoot->value;
    }

    minVal = leftMin < rightMin ? leftMin : rightMin;
    maxVal = leftMax > rightMax ? leftMax : rightMax;

    return true;
}
Risposto il 13/02/2012 a 21:08
fonte dall'utente

voti
0
// using inorder traverse based Impl
bool BinarySearchTree::validate() {
    int val = -1;
    return ValidateImpl(root, val);
}

// inorder traverse based Impl
bool BinarySearchTree::ValidateImpl(Node *currRoot, int &val) {
    if (currRoot == NULL) return true;

    if (currRoot->left) {
        if (currRoot->left->value > currRoot->value) return false;
        if(!ValidateImpl(currRoot->left, val)) return false;
    }

    if (val > currRoot->value) return false;
    val = currRoot->value;

    if (currRoot->right) {
        if (currRoot->right->value < currRoot->value) return false;
        if(!ValidateImpl(currRoot->right, val)) return false;
    }
    return true;
}
Risposto il 14/02/2012 a 10:34
fonte dall'utente

voti
-3
boolean isBST(Node root) {
    if (root == null) { return true; }
    return (isBST(root.left) && (isBST(root.right) && (root.left == null || root.left.data <= root.data) && (root.right == null || root.right.data > root.data));
}
Risposto il 05/03/2012 a 23:45
fonte dall'utente

voti
-1

Ecco la soluzione iterativa senza utilizzare spazio extra.

Node{
     int value;
     Node right, left
  }

  public boolean ValidateBST(Node root){
    Node currNode = root;
    Node prevNode = null;
    Stack<Node> stack = new Stack<Node>();
    while(true){
        if(currNode != null){
            stack.push(currNode);
            currNode = currNode.left;
            continue;
        }
        if(stack.empty()){
            return;
        }
        currNode = stack.pop();
        if(prevNode != null){
            if(currNode.value < prevNode.value){
                return false;
            }
        }
        prevNode = currNode;
        currNode = currNode.right;
    }
}
Risposto il 07/04/2012 a 02:07
fonte dall'utente

voti
1
bool ValidateBST(Node *pCurrentNode, int nMin = INT_MIN, int nMax = INT_MAX)
{
    return
    (
        pCurrentNode == NULL
    )
    ||
    (
        (
            !pCurrentNode->pLeftNode ||
            (
                pCurrentNode->pLeftNode->value < pCurrentNode->value &&
                pCurrentNode->pLeftNode->value < nMax &&
                ValidateBST(pCurrentNode->pLeftNode, nMin, pCurrentNode->value)
            )
        )
        &&
        (
            !pCurrentNode->pRightNode ||
            (
                pCurrentNode->pRightNode->value > pCurrentNode->value &&
                pCurrentNode->pRightNode->value > nMin &&
                ValidateBST(pCurrentNode->pRightNode, pCurrentNode->value, nMax)
            )
        )
    );
}
Risposto il 20/05/2012 a 03:33
fonte dall'utente

voti
12

La soluzione migliore che ho trovato è O (n) e non utilizza spazio aggiuntivo. È simile a ordine simmetrico ma invece di immagazzinarla a matrice e poi verificare se è ordinato possiamo prendere una variabile statica e controllare che il simmetrico attraversamento se array è ordinato.

static struct node *prev = NULL;

bool isBST(struct node* root)
{
    // traverse the tree in inorder fashion and keep track of prev node
    if (root)
    {
        if (!isBST(root->left))
          return false;

        // Allows only distinct valued nodes
        if (prev != NULL && root->data <= prev->data)
          return false;

        prev = root;

        return isBST(root->right);
    }

    return true;
}
Risposto il 06/06/2012 a 08:14
fonte dall'utente

voti
0

Per scoprire se dato BT è BST per qualsiasi tipo di dati, è necessario andare con avvicinamento al di sotto. 1. chiamata di funzione ricorsiva fino alla fine del nodo foglia con ordine simmetrico 2. Costruisci la tua min e max dei valori stessi.

elemento albero deve avere meno di / maggiore di operatore definito.

#define MIN (FirstVal, SecondVal) ((FirstVal) < (SecondVal)) ? (FirstVal):(SecondVal)
#define MAX (FirstVal, SecondVal) ((FirstVal) > (SecondVal)) ? (FirstVal):(SecondVal)

template <class T>
bool IsValidBST (treeNode &root)
{

   T min,  max;
   return IsValidBST (root, &min, &max);
}

template <class T>
bool IsValidBST (treeNode *root, T *MIN , T *MAX)
{
   T leftMin, leftMax, rightMin, rightMax;
   bool isValidBST;

   if (root->leftNode == NULL && root->rightNode == NULL)
   {
      *MIN = root->element;
      *MAX = root->element;
      return true;
   }

  isValidBST = IsValidBST (root->leftNode, &leftMin, &leftMax);

  if (isValidBST)
    isValidBST = IsValidBST (root->rightNode, &rightMin, &rightMax);

  if (isValidBST)
  {
     *MIN = MIN (leftMIN, rightMIN);
     *Max = MAX (rightMax, leftMax);
  }

  return isValidBST;
}
Risposto il 13/06/2012 a 18:16
fonte dall'utente

voti
0
bool isBST(struct node* root)
{
    static struct node *prev = NULL;
    // traverse the tree in inorder fashion and keep track of prev node
    if (root)
    {
        if (!isBST(root->left))
            return false;
        // Allows only distinct valued nodes
        if (prev != NULL && root->data <= prev->data)
            return false;
        prev = root;
        return isBST(root->right);
    }
    return true;
}

Funziona bene :)

Risposto il 28/06/2012 a 11:24
fonte dall'utente

voti
0

La ricorsione è facile, ma approccio iterativo è meglio, c'è una versione iterativa sopra, ma è troppo complessa del necessario. Ecco la migliore soluzione in c++potrai mai trovato sul web:

Questo algoritmo viene eseguito in O(N)tempo e ha bisogno di O(lgN)spazio.

struct TreeNode
{
    int value;
    TreeNode* left;
    TreeNode* right;
};

bool isBST(TreeNode* root) {
    vector<TreeNode*> stack;
    TreeNode* prev = nullptr;
    while (root || stack.size()) {
        if (root) {
           stack.push_back(root);
           root = root->left;
        } else {
            if (prev && stack.back()->value <= prev->value)
                return false;
            prev = stack.back();
            root = prev->right;                    
            stack.pop_back();
        }
    }
    return true;
}
Risposto il 04/11/2012 a 07:20
fonte dall'utente

voti
0

Ho scritto una soluzione da usare ordine simmetrico BST e controllare se i nodi vengono ordine crescente per lo spazio O(1)e il tempo O(n). TreeNode predecessorè prev nodo. Non sono sicuro che la soluzione è giusta o no. Perché l'ordine simmetrico non può definire un intero albero.

public boolean isValidBST(TreeNode root, TreeNode predecessor) {
    boolean left = true, right = true;
    if (root.left != null) {
        left = isValidBST(root.left, predecessor);
    }
    if (!left)
        return false;

    if (predecessor.val > root.val)
        return false;

    predecessor.val = root.val;
    if (root.right != null) {
        right = isValidBST(root.right, predecessor);
    }

    if (!right)
        return false;

    return true;

}
Risposto il 16/02/2013 a 03:25
fonte dall'utente

voti
0

Di seguito è riportato l'implementazione Java di convalida BST, dove viaggiamo struttura DFS in ordine e restituisce false se otteniamo un qualsiasi numero che è più grande rispetto allo scorso numero.

static class BSTValidator {
  private boolean lastNumberInitialized = false;
  private int lastNumber = -1;

  boolean isValidBST(TreeNode node) {
    if (node.left != null && !isValidBST(node.left)) return false;

    // In-order visiting should never see number less than previous
    // in valid BST.
    if (lastNumberInitialized && (lastNumber > node.getData())) return false;
    if (!lastNumberInitialized) lastNumberInitialized = true;

    lastNumber = node.getData();

    if (node.right != null && !isValidBST(node.right)) return false;

    return true;
  }
}
Risposto il 18/01/2014 a 06:58
fonte dall'utente

voti
3

Dal momento che l'attraversamento in ordine di un BST è una sequenza non diminuire, potremmo utilizzare questa proprietà per giudicare se un albero binario è BST o meno. Utilizzando Morris attraversamento e mantenendo il prenodo, potremmo ottenere una soluzione in O (n) e O (1) spazio complessità. Ecco il mio codice

public boolean isValidBST(TreeNode root) {
    TreeNode pre = null, cur = root, tmp;
    while(cur != null) {
        if(cur.left == null) {
            if(pre != null && pre.val >= cur.val) 
                return false;
            pre = cur;
            cur = cur.right;
        }
        else {
            tmp = cur.left;
            while(tmp.right != null && tmp.right != cur)
                tmp = tmp.right;
            if(tmp.right == null) { // left child has not been visited
                tmp.right = cur;
                cur = cur.left;
            }
            else { // left child has been visited already
                tmp.right = null;
                if(pre != null && pre.val >= cur.val) 
                    return false;
                pre = cur;
                cur = cur.right;
            }
        }
    }
    return true;
}
Risposto il 18/10/2014 a 20:13
fonte dall'utente

voti
1

Ho avuto questa domanda in un'intervista telefonica di recente e lottato con più di quanto avrei dovuto. Stavo cercando di tenere traccia dei minimi e massimi nei nodi figlio e io non riuscivo a avvolgere il mio cervello intorno i diversi casi sotto la pressione di un colloquio.

Dopo averci pensato mentre addormentarsi la notte scorsa, mi sono reso conto che è così semplice come tenere traccia dell'ultimo nodo che hai visitato durante un attraversamento in ordine simmetrico. In Java:

public <T extends Comparable<T>> boolean isBst(TreeNode<T> root) {
    return isBst(root, null);
}

private <T extends Comparable<T>> boolean isBst(TreeNode<T> node, TreeNode<T> prev) {
    if (node == null)
        return true;

    if (isBst(node.left, prev) && (prev == null || prev.compareTo(node) < 0 ))
        return isBst(node.right, node);

    return false;
}
Risposto il 10/12/2014 a 05:21
fonte dall'utente

voti
0

soluzione iterativa.

private static boolean checkBst(bst node) {

    Stack<bst> s = new Stack<bst>();
    bst temp;
    while(node!=null){
        s.push(node);
        node=node.left;
    }
    while (!s.isEmpty()){
        node = s.pop();
        System.out.println(node.val);
        temp = node;
        if(node.right!=null){
            node = node.right;
            while(node!=null)
            {
                //Checking if the current value is lesser than the previous value and ancestor.
                if(node.val < temp.val)
                    return false;
                if(!s.isEmpty())
                    if(node.val>s.peek().val)
                        return false;
                s.push(node);
                if(node!=null)
                node=node.left;
            }
        }
    }
    return true;
}
Risposto il 15/12/2014 a 14:44
fonte dall'utente

voti
0

Questo funziona per i duplicati.

// time O(n), space O(logn)
// pseudocode
is-bst(node, min = int.min, max = int.max):
    if node == null:
        return true
    if node.value <= min || max < node.value:
        return false
    return is-bst(node.left, min, node.value)
        && is-bst(node.right, node.value, max)

Questo funziona anche per int.mine int.maxvalori usando Nullablei tipi.

// time O(n), space O(logn)
// pseudocode
is-bst(node, min = null, max = null):
    if node == null:
        return true
    if min != null && node.value <= min
        return false
    if max != null && max < node.value:
        return false
    return is-bst(node.left, min, node.value)
        && is-bst(node.right, node.value, max)
Risposto il 25/03/2015 a 08:16
fonte dall'utente

voti
0

Ispirato da http://www.jiuzhang.com/solutions/validate-binary-search-tree/

Ci sono due soluzioni generali: attraversamento e dividere && impera.

public class validateBinarySearchTree {
    public boolean isValidBST(TreeNode root) {
        return isBSTTraversal(root) && isBSTDivideAndConquer(root);
    }

    // Solution 1: Traversal
    // The inorder sequence of a BST is a sorted ascending list
    private int lastValue = 0; // the init value of it doesn't matter.
    private boolean firstNode = true;
    public boolean isBSTTraversal(TreeNode root) {
        if (root == null) {
            return true;
        }

        if (!isValidBST(root.left)) {
            return false;
        }

        // firstNode is needed because of if firstNode is Integer.MIN_VALUE,
        // even if we set lastValue to Integer.MIN_VALUE, it will still return false
        if (!firstNode && lastValue >= root.val) {
            return false;
        }

        firstNode = false;
        lastValue = root.val;

        if (!isValidBST(root.right)) {
            return false;
        }

        return true;

    }

    // Solution 2: divide && conquer
    private class Result {
        int min;
        int max;
        boolean isBST;
        Result(int min, int max, boolean isBST) {
            this.min = min;
            this.max = max;
            this.isBST = isBST;
        }
    }

    public boolean isBSTDivideAndConquer(TreeNode root) {
        return isBSTHelper(root).isBST;
    }

    public Result isBSTHelper(TreeNode root) {
        // For leaf node's left or right
        if (root == null) {
            // we set min to Integer.MAX_VALUE and max to Integer.MIN_VALUE
            // because of in the previous level which is the leaf level,
            // we want to set the min or max to that leaf node's val (in the last return line)
            return new Result(Integer.MAX_VALUE, Integer.MIN_VALUE, true);
        }

        Result left = isBSTHelper(root.left);
        Result right = isBSTHelper(root.right);

        if (!left.isBST || !right.isBST) {
            return new Result(0,0, false);
        }

        // For non-leaf node
        if (root.left != null && left.max >= root.val
                && root.right != null && right.min <= root.val) {
            return new Result(0, 0, false);
        }

        return new Result(Math.min(left.min, root.val),
                Math.max(right.max, root.val), true);
    }
}
Risposto il 07/10/2015 a 05:24
fonte dall'utente

voti
-3

Qui è la mia soluzione ricorsiva scritto in JavaScript

function isBST(tree) {
  if (tree === null) return true;

  if (tree.left != undefined && tree.left.value > tree.value) {
    return false;
  }

  if (tree.right != undefined && tree.right.value <= tree.value) {
    return false;
  }

  return isBST(tree.left) && isBST(tree.right);
}
Risposto il 19/10/2015 a 03:29
fonte dall'utente

voti
1

In Java e consentendo nodi con lo stesso valore in entrambi i sotto-albero:

public boolean isValid(Node node) {
    return isValid(node, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

private boolean isValid(Node node, int minLimit, int maxLimit) {
    if (node == null)
        return true;
    return minLimit <= node.value && node.value <= maxLimit
            && isValid(node.left, minLimit, node.value)
            && isValid(node.right, node.value, maxLimit);
}
Risposto il 10/09/2016 a 05:03
fonte dall'utente

voti
-1
 private void validateBinarySearchTree(Node node) {
    if (node == null) return;

    Node left = node.getLeft();
    if (left != null) {
        if (left.getData() < node.getData()) {
            validateBinarySearchTree(left);
        } else {
            throw new IllegalStateException("Not a valid Binary Search tree");
        }
    }

    Node right = node.getRight();
    if (right != null) {
        if (right.getData() > node.getData()) {
            validateBinarySearchTree(right);
        } else {
            throw new IllegalStateException("Not a valid Binary Search tree");
        }
    }
}
Risposto il 20/11/2017 a 20:30
fonte dall'utente

voti
2

Ecco la mia risposta in python, dispone di tutti i casi d'angolo affrontati e ben testato in sito hackerrank

""" Node is defined as
class node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
"""

def checkBST(root):
    return checkLeftSubTree(root, root.left) and checkRightSubTree(root, root.right)

def checkLeftSubTree(root, subTree):
    if not subTree:
        return True
    else:
        return root.data > subTree.data \
        and checkLeftSubTree(root, subTree.left) \ 
        and checkLeftSubTree(root, subTree.right) \
        and checkLeftSubTree(subTree, subTree.left) \
        and checkRightSubTree(subTree, subTree.right)

def checkRightSubTree(root, subTree):
    if not subTree:
        return True
    else:
        return root.data < subTree.data \ 
        and checkRightSubTree(root, subTree.left) \
        and checkRightSubTree(root, subTree.right) \
        and checkRightSubTree(subTree, subTree.right) \
        and checkLeftSubTree(subTree, subTree.left)
Risposto il 26/12/2017 a 18:04
fonte dall'utente

voti
0

uno di linea

bool is_bst(Node *root, int from, int to) {
   return (root == NULL) ? true :
     root->val >= from && root->val <= to &&
     is_bst(root->left, from, root->val) &&
     is_bst(root->right, root->val, to);
}

Piuttosto lunga fila però.

Risposto il 15/01/2018 a 19:12
fonte dall'utente

voti
0

Ecco una soluzione in java dalla classe algoritmo di Sedgewick. Controllare l'attuazione piena BST qui

Ho aggiunto alcuni commenti esplicativi

private boolean isBST() {
    return isBST(root, null, null);

}

private boolean isBST(Node x, Key min, Key max) {
    if (x == null) return true;
    // when checking right subtree min is key of x's parent
    if (min != null && x.key.compareTo(min) <= 0) return false;
    // when checking left subtree, max is key of x's parent
    if (max != null && x.key.compareTo(max) >= 0) return false;
    // check left subtree and right subtree
    return isBST(x.left, min, x.key) && isBST(x.right, x.key, max);

}
Risposto il 30/10/2018 a 23:02
fonte dall'utente

voti
0
  • La iterativefunzione controlla in modo iterativo se dato albero è un albero binario di ricerca.
  • La recursefunzione controlla in modo ricorsivo se dato albero è un albero binario di ricerca o no.
  • In iterativefunzione di uso BFS per il controllo BST.
  • In recursefunzione I utilizzare DFS per il controllo BST.
  • Entrambe le soluzioni hanno una complessità temporale O(n)
  • iterativesoluzione ha un vantaggio rispetto recursesoluzione e che è iterativela soluzione fa arresto precoce.
  • Anche recursela funzione può essere ottimizzato per l'arresto precoce per valore flag globale.
  • L'idea di e la soluzione è che il bambino sinistra dovrebbe essere nell'intervallo di -Infinity al valore del suo nodo padre whihch è il nodo radice
  • Il bambino destra dovrebbe essere nel range di + infinito per il valore del suo nodo padre whihch è il nodo principale
  • E vai sul confronto tra il valore del nodo corrente all'interno della gamma. Se il valore di ogni nodo non è nel range poi tornare False

    class Solution:
        def isValidBST(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            return self.iterative(root)
            # return self.recurse(root, float("inf"), float("-inf"))
    
        def iterative(self, root):
            if not root:
                return True
    
            level = [[root, -float("inf"), float("inf")]]
    
            while level:
                next_level = []
    
                for element in level:
                    node, min_val, max_val = element
                    if min_val<node.val<max_val:
                        if node.left:
                            next_level.append([node.left, min_val, node.val])
                        if node.right:
                            next_level.append([node.right, node.val, max_val])
                    else:
                        return False
                level = next_level
    
            return True
    
        def recurse(self, root, maxi, mini):
            if root is None:
                return True
    
            if root.val < mini or root.val > maxi:
                return False
    
            return self.recurse(root.left, root.val-1, mini) and self.recurse(root.right, maxi, root.val+1)
    
Risposto il 01/11/2018 a 03:22
fonte dall'utente

voti
0

attuazione pitone esempio. Questo esempio utilizza annotazioni di tipo. Tuttavia, poiché classe Node stesso utilizza dobbiamo includere come una prima linea del modulo:

from __future__ import annotations

In caso contrario, si otterrà name 'Node' is not definedl'errore. Questo esempio utilizza anche classe di dati come esempio. Per verificare se si tratta di BST utilizza la ricorsione per il controllo dei valori nodi a destra ea sinistra.

"""Checks if Binary Search Tree (BST) is balanced"""

from __future__ import annotations
import sys
from dataclasses import dataclass

MAX_KEY = sys.maxsize
MIN_KEY = -sys.maxsize - 1


@dataclass
class Node:
    value: int
    left: Node
    right: Node

    @property
    def is_leaf(self) -> bool:
        """Check if node is a leaf"""
        return not self.left and not self.right


def is_bst(node: Node, min_value: int, max_value: int) -> bool:
    if node.value < min_value or max_value < node.value:
        return False
    elif node.is_leaf:
        return True

    return is_bst(node.left, min_value, node.value) and is_bst(
        node.right, node.value, max_value
    )


if __name__ == "__main__":
    node5 = Node(5, None, None)
    node25 = Node(25, None, None)
    node40 = Node(40, None, None)
    node10 = Node(10, None, None)

    # balanced tree
    node30 = Node(30, node25, node40)
    root = Node(20, node10, node30)
    print(is_bst(root, MIN_KEY, MAX_KEY))

    # unbalanced tree
    node30 = Node(30, node5, node40)
    root = Node(20, node10, node30)
    print(is_bst(root, MIN_KEY, MAX_KEY))
Risposto il 16/01/2019 a 00:10
fonte dall'utente

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more