二叉搜索树的实现,反转,前序,中序,后序,层序的遍历 --自我记录

423 阅读2分钟

//二叉树一般会有一个节点的node类还有tree树类,树里面会有根节点root
class Node {
constructor(element, parent) {
this.element = element
this.parent = parent
this.left = null
this.right = null
}
}

// 树类
class Tree {

constructor() {
    this.root = null //树类默认为nul
}

add(element) { //增加树杈的方法
    //第一步逻辑考虑首次添加判断root为null
    if (this.root === null) {
        this.root = new Node(element, null)
        return
    }
    //如果非首次添加节点,那就需要去除根节点一层一层的取值去比较,看是放在左边还是右边
    let root = this.root
    let parent
    let compare
    while (root) { //有多个深层次节点的话循环不停的去取
        parent = root
        compare = root.element > element //root一旦为null就说明已经循环到底了
        if (compare) { //如果跟节点比传入的大放左边反之右边,考虑深度的情况下继续去取左边的left
            root = root.left
        } else {
            root = root.right
        }
    }

    if (compare) {
        parent.left = new Node(element, parent)
    } else {
        parent.right = new Node(element, parent)
    }
}

//前序遍历,先遍历根节点然后遍历左边再遍历右边
preorder() {
    function a(node) {
        if (node === null) return
        console.log(node); //通过打印的顺序来模拟
        a(node.left)
        a(node.right)
    }
    a(this.root)

}


//中序遍历,先遍历左边然后中间,最后右边
middle() {
    function a(node) {
        if (node === null) return
        a(node.left)
        console.log(node); //通过打印的顺序来模拟
        a(node.right)
    }
    a(this.root)

}


//后序遍历,是先遍历左子树,然后是右子树,最后才是中间的根节点
epilogue() {
    function a(node) {
        if (node === null) return
        a(node.left)
        a(node.right)
        console.log(node); //通过打印的顺序来模拟
    }
    a(this.root)

}

//层序遍历 一层一层去 遍历 层序遍历利用栈去完成,取出一个个放进去,然后
sequence() {
    let stack = [] //栈数组去存放

    stack.push(this.root) //先放入根元素
    while (stack.length) {
        let ele = stack.shift() //首先是取出根元素
        console.log(ele);
        if (ele.left) {
            stack.push(ele.left)
        }

        if (ele.right) {
            stack.push(ele.right)
        }


    }

}

//树的反转是利用层序的时候去互换,类似于冒泡排序
reserve() {
    let stack = [] //栈数组去存放

    stack.push(this.root) //先放入根元素
    while (stack.length) {
        let ele = stack.shift() //首先是取出根元素

        //取出这个元素后就看看他的左右有没有有的话就互相
        let temp = ele.left
        ele.left = ele.right
        ele.right = temp
        console.log(ele);
        if (ele.left) {
            stack.push(ele.left)
        }

        if (ele.right) {
            stack.push(ele.right)
        }


    }

}

}

let tree = new Tree()
tree.add(10)
tree.add(8)
tree.add(6)
tree.add(19)
tree.add(15)
tree.add(22)
tree.add(20)

// tree.preorder() 前序
// tree.middle() 中序
// tree.epilogue() //后序
// tree.sequence() //层序
tree.reserve()//反转
// console.dir(tree, {
// depth: 100
// });