编辑代码

// 定义节点结构,当前节点值和左右节点
var Node = function (data, left, right) {
  this.data = data;
  this.left = left;
  this.right = right;
};
// 打印树结构
Node.prototype.show = function () {
  console.log("data:", this.data, "left:", this.left, "right:", this.right);
};

// 测试
console.log("测试Node");
new Node(3, 1, 4).show();

// 定义树结构
var Tree = function () {
  // root表示根节点,插入的第一个元素为其根节点
  this.root = null;
};
Tree.prototype = {
  constructor: Tree,
  show: function () {
    console.groupEnd(this.root);
  },
  // 插入节点
  insert: function (data) {
    // 插入的节点暂时没有左右节点
    var node = new Node(data, null, null);

    // 没有根节点,则node为根节点(第一次插入)
    if (!this.root) {
      this.root = node;
      return;
    }

    // 非第一次插入
    // current为子节点的根节点,用于判断插入位置是左还是右
    // root为对象,引用类型
    let current = this.root;

    while (current) {
      // 小于根节点,应该插入左侧
      if (data < current.data) {
        if (!current.left) {
          current.left = node;
          break;
          // break手动终止循环
        } else {
          current = current.left;
        }
      } else {
        // 相等、大于 插入右侧
        if (!current.right) {
          current.right = node;
          break;
          // break手动终止循环
        } else {
          current = current.right;
        }
      }
    }
  },
  //  获取树深度
  getDeep() {},

  getNode(data, root) {
    if (root) {
      if (data == root.data) {
        return root;
      } else if (data < root.data) {
        return this.getNode(data, root.left);
      } else {
        return this.getNode(data, root.right);
      }
    } else {
      return null;
    }
  },
  getNodeFn(root) {
    root = root || this.root;

    return (data) => {
      if (root) {
        if (data == root.data) {
          return root;
        } else if (data < root.data) {
          return this.getNode(data, root.left);
        } else {
          return this.getNode(data, root.right);
        }
      } else {
        return null;
      }
    };
  },
};
console.log("测试Tree");
var t = new Tree();
t.insert(7);
t.insert(2);
t.insert(5);
t.insert(1);
t.insert(3);
t.insert(4);
t.insert(6);

t.insert(8);
t.show();
console.log("getNode");
let fn = t.getNodeFn();
fn(3).show();