zl程序教程

您现在的位置是:首页 >  后端

当前栏目

二叉树——前序、中序、后序遍历

二叉树遍历 中序 后序 前序
2023-09-11 14:16:24 时间

前序遍历

根 -> 左 -> 右

Tree.prototype.prevOrder=function(){
    let stack = [];//表示栈
    let values=[];//values存储的是节点的值
    if(this.root==null){
        return;
    }
    stack.push(this.root);//让根节点入栈
    while(stack.lenght>0){
        let currentNode = stack.pop();//弹出并获取栈顶的元素
        //将栈顶元素的值放入数组
        values.push(currentNode.value);
        // 因为栈是先进后出,最后出来的应该是右节点,所以右节点先进 
        //让当前节点的右节点入栈,然后左节点入栈,必需确保左右节点不为空
        let rightNode=currentNode.right;
        let leftNode=currentNode.left;
        if(rightNode!=null){
            stack.push(currentNode.right);
        }
        if(leftNode!=null){
            stack.push(currentNode.left);
        }
    }
    return values;
}

中序遍历

左 -> 根 -> 右

Tree.prototype.middleOrder=function(){
    let stack=[];
    let values=[];
    if(!this.root){
        return;
    }
    let currentNode=this.root;
    while(currentNode!=null||stack.length>0){
        while(currentNode!=null){
            stack.push(currentNode)
            currentNode= currentNode.left;
        }
        if(stack.length>0){
            let node=stack.pop();
            values.push(node.value);
            let rightNode=node.right;
            currentNode=rightNode;
        }
    }
    return values;
}

后序遍历

左 -> 右 -> 根

Tree.prototype.afterOrder=function(){
    if(!this.root){
        return;
    }
    let stack=[];
    let values=[];
    stack.push(this.root)
    while(stack.length>0){
       let node =  stack.pop();
       values.push(node.value)
       if(node.left){
            stack.push(node.left)
       }
       if(node.right){
            stack.push(node.right)
       }
    }
    return values.reverse();
}