利用棧實現二叉樹的先序、中序、后序遍歷


先序:A->B->D->E->C->F->G

function preTraverStack(root,cb){
    let stack = new Stack()
    stack.push(root)
    while(!stack.isEmpty()){
        let node = stack.pop()
        if(node.right != null){
            stack.push(node.right)
        }
        if(node.left != null){
            stack.push(node.left)
        }
        cb(node.val)
    }
}
function preTraver(root,cb){
    let arr = []
    arr.push(root)
    while(arr.length != 0){
        let node  = arr.pop()
        if(node.right != null){
            arr.push(node.right)
        }
        if(node.left != null){
            arr.push(node.left)
        }
        cb(node.val)
    }
}

中序:D->B->E->A->F->C->G

function inTraverStack(root,cb){
    let stack = new Stack()
    stack.push(root)
    while(!stack.isEmpty()){
        while(stack.peek().left != null){
            stack.push(stack.peek().left)
        }
        while(!stack.isEmpty()){
            let node = stack.pop()
            cb(node.val)
            if(node.right != null){
                stack.push(node.right)
                break
            }
        }
    }
}
function inTraver(root,cb){
    let arr = []
    arr.push(root)
    while(arr.length != 0){
        while(arr[arr.length - 1].left != null){
            arr.push(arr[arr.length - 1].left)
        }
        while(arr.length != 0){
            let node = arr.pop()
            cb(node.val)
            if(node.right != null){
                arr.push(node.right)
                break
            }
        }
    }
}

后序:D->E->B->F->G->C->A

function postTraverStack(root,cb){
    let stack = new Stack()
    stack.push(root)
    let lastNode = null
    while(!stack.isEmpty()){
        while(stack.peek().left != null){
            stack.push(stack.peek().left)
        }
        while(!stack.isEmpty()){
            if(lastNode == stack.peek().right || stack.peek().right == null){
                let node = stack.pop()
                cb(node.val)
                lastNode = node
            }else if(stack.peek().right != null){
                stack.push(stack.peek().right)
                break
            }
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM