关于javascript:数据结构JavaScript-Binary-Tree-实现

残缺可运行代码

class Tree {
  constructor(element) {
    this.element = element
    this.left = null
    this.right = null
  }
  //中序遍历
  traversal() {
    console.log(this.element)
    if(this.left !== null) {
      this.left.traversal()
    }
    if(this.right !== null) {
      this.right.traversal()
    }
  }
  // 反转二叉树
  reverse() {
    let temp = this.left
    this.left = this.right 
    this.right = temp
    if(this.left !== null) {
      this.left.reverse()
    }
    if(this.right !== null) {
      this.right.reverse()
    }
  }
}

// 
let t = new Tree(0)
let left = new Tree(1)
let right = new Tree(2)
t.left = left
t.right = right

t.traversal()
t.reverse()
t.traversal()

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理