完整可运行代码

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()

TaoWu
15 声望2 粉丝