Issue checking if binary tree is also binary search tree

前端 未结 4 1671
-上瘾入骨i
-上瘾入骨i 2021-01-19 04:12

I\'m trying to solve this problem but I\'m having some troubles:

In a binary search tree (BST):

  • The data value of every node in a
4条回答
  •  感动是毒
    2021-01-19 04:54

    Something like the following should work

    boolean check(Node root) {   
    
        if (root == null) {
            return true;
        }
    
    
        if (root.left != null && max(root.left) > root.data  ) {
            return false
        }
    
        if (root.right != null && max(root.right) < root.data ) {
            return false;
        }
    
        return check(root.left) && check(root.right);
    }
    

    Note:

    • this is fairly inefficient
    • you need to implement max()

提交回复
热议问题