打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
构造并判断二叉搜索树-js


class Node {  constructor (val) {    this.val = val    this.left = this.right = undefined  }}class Tree {  constructor (data) {    let root = new Node(data.shift())    // 遍历所有的数据    data.forEach(item => {      this.insert(root, item)    })    return root  }  insert (node, data) {    if (node.val > data) {      if (node.left === undefined) {        node.left = new Node(data)      } else {        this.insert(node.left, data)      }    } else {      if (node.right === undefined) {        node.right = new Node(data)      } else {        this.insert(node.right, data)      }    }  }  static walk (root) {    if (!root.left && !root.right) {      return true    } else if ((root.left && root.val < root.left.val) || (root.right && root.val > root.right.val)) {      return false    } else {      return Tree.walk(root.left) && Tree.walk(root.right)    }  }}export default Treeexport {  Node}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
0111. Minimum Depth of Binary Tree (E)
0173. Binary Search Tree Iterator (M)
LeetCode 101. 对称二叉树(Symmetric Tree)
序列化二叉树
050.二叉搜索树操作
Linux调试技术(三)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服