[Algorithm] Check if a binary tree is binary search tree or not

What is Binary Search Tree (BST)

A binary tree in which for each node, value of all the nodes in left subtree is less or equal and value of all the nodes in right subtree is greater

 

The idea:

We can use set boundry for each node. We take C tree for example:

For root node, the B (bountry) = [MIN, MAX]

node 4: B = [MIN, 7] // cannot be greater than 7

node 1: B = [MIN, 4]

node 6: B = [4, 7] // cannot less than 4, but should less than 7.

node 9: B = [7, MAX] // cannot less than 7

 

复制代码
function Node(val) {
  return {
    val,
    left: null,
    right: null
  };
}

function Tree() {
  return {
    root: null,
    addLeft(val, root) {
      const node = Node(val);
      root.left = node;
      return root.left;
    },
    addRight(val, root) {
      const node = Node(val);
      root.right = node;
      return root.right;
    }
  };
}

function isBinarySearchTree(root) {
  function helper(root, max, min) {
    if (root == null) {
      return true;
    }

    if (
      root.val >= min &&
      root.val <= max &&
      helper(root.left, root.val, min) &&
      helper(root.right, max, root.val)
    ) {
      return true;
    } else {
      return false;
    }
  }

  return helper(root, Number.MAX_VALUE, Number.MIN_VALUE);
}

const tree = new Tree();
const root = Node(10);
tree.root = root;
const ll1 = tree.addLeft(5, tree.root);
tree.addRight(16, tree.root);
const ll2 = tree.addLeft(4, ll1);
const lr2 = tree.addRight(7, ll1);
tree.addLeft(1, ll2);
tree.addRight(11, lr2);
tree.addRight(16, tree.root);

/*
             10
           /    \
         5       16
       /   \
     4      7 
    /        \
  1           11  

11 is greater than 10, which is false

*/

const res1 = isBinarySearchTree(root); // false
console.log(res1);

const tree2 = new Tree();
const root2 = Node(7);
tree2.root = root2;
const _ll1 = tree.addLeft(4, tree.root);
tree.addRight(9, tree.root);
tree.addLeft(1, _ll1);
tree.addRight(6, _ll1);

/*

          7
         / \  
       4    9 
      / \
     1   6
*/

const res2 = isBinarySearchTree(root2); // true
console.log(res2);
复制代码

 

posted @   Zhentiw  阅读(328)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-04-01 [Typescript] Function defination
点击右上角即可分享
微信分享提示