js数据结构之树(tree)

时间:2025-04-06 19:25:53
  • // 定义Node节点
  • class Node {
  • constructor (value) {
  • this.value = value,
  • this.left = null,
  • this.right = null
  • }
  • }
  • class Tree {
  • constructor () {
  • = null // 首先定义根节点 为null
  • }
  • // 寻找插入节点
  • insertNode (node, CurrentNode){
  • if (node.value > CurrentNode.value) {
  • if (CurrentNode.right) {
  • (node, CurrentNode.right) // 递归 继续向下寻找
  • } else {
  • CurrentNode.right = node
  • }
  • } else if (node.value < CurrentNode.value) {
  • if (CurrentNode.left) {
  • (node, CurrentNode.left) // 递归 继续向下寻找
  • } else {
  • CurrentNode.left = node
  • }
  • }
  • }
  • // 插入
  • insert (value) {
  • var node = new Node(value)
  • if () {
  • (node, )
  • // 因为要递归 所以 单独封装方法
  • } else {
  • = node // 没有根节点 设置为根节点
  • }
  • }
  • // 遍历节点
  • traverse (callback) {
  • (, callback)
  • }
  • traver(node, callback) {
  • if (node === null) {
  • return
  • }
  • (node.left, callback)
  • callback(node.value) // 中序遍历 后序遍历 前序遍历等等高改变这行代码位置
  • (node.right, callback)
  • }
  • // 删除节点
  • remove () {
  • }
  • // 二叉树最小值 找到最左节点
  • getMin () {
  • // 空树返回null
  • if ( === null) {
  • return null
  • }
  • var current =
  • while(current.left) {
  • current = current.left
  • }
  • return current.value
  • }
  • // 获取二叉树搜索树最大值 最右节点
  • getMax () {
  • // 空树返回null
  • if ( === null) {
  • return null
  • }
  • var current =
  • while(current.right) {
  • current = current.right
  • }
  • return current.value
  • }
  • // 获取树
  • getTree () {
  • return
  • }
  • }
  • var tree = new Tree()
  • (12)
  • (13)
  • (4)
  • (13)
  • (())
  • ((value) => {
  • ('VALUE', value)
  • })
  • (())
  • (ax())