码迷,mamicode.com
首页 > 编程语言 > 详细

数据结构算法实现-二叉树遍历的非递归算法

时间:2017-04-08 00:30:12      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:递归   16px   数据结构   树遍历   使用   return   堆栈   div   算法   

由于递归算法使用系统堆栈,性能较差,所以应尽可能使用非递归算法。

1.先序遍历

先序遍历,即得到节点时输出数据。

// 先序遍历    
function PreOrder(node){
    if(node!==undefined){
        console.log(node.data)
    }
    var stack=[] //模仿递归的栈
    stack.push(node)
    for(var temp=node,i=0;temp!==undefined;temp=stack[stack.length-1]){
        if(temp.lChild!==null){
            console.log(array[temp.lChild].data)
            //遍历后即将引用设为null
            var lChild=array[temp.lChild] 
            temp.lChild=null
            stack.pop()
            stack.push(temp)
            stack.push(lChild)
        }else if(temp.rChild!==null){
            console.log(array[temp.rChild].data)
            //遍历后即将引用设为null
            var rChild=array[temp.rChild]
            temp.rChild=null
            stack.pop()
            stack.push(temp)
            stack.push(rChild)
        }else{
            stack.pop()
        }
    }

}

var array=BinaryTree()
PreOrder(array[0])

 

输出

a b d c e f

 

 

2.中序遍历

中序遍历也即等到所有左分支都遍历完成后,才开始输出。

// 中序遍历    
function InOrder(node){
    if(node===undefined) return
var stack=[] //模仿递归的栈 stack.push(node) for(var temp=node,i=0;temp!==undefined;temp=stack[stack.length-1]){ if(temp.lChild!==null){ //遍历后即将引用设为null var lChild=array[temp.lChild] temp.lChild=null stack.pop() stack.push(temp) stack.push(lChild) }else{ if(temp.data!==undefined){ console.log(temp.data) } temp.data=undefined if(temp.rChild!==null){ //遍历后即将引用设为null var rChild=array[temp.rChild] temp.rChild=null stack.pop() stack.push(temp) stack.push(rChild) }else{ stack.pop() } } } } var array=BinaryTree() InOrder(array[0])

输出 b d a c f e

 

3.后序遍历

也即等到左右分支都遍历完成后,才开始输出。

// 后序遍历    
function PostOrder(node){
    if(node===undefined) return
    
    var stack=[] //模仿递归的栈
    stack.push(node)
    for(var temp=node;temp!==undefined;temp=stack[stack.length-1]){
        if(temp.lChild!==null){
            //遍历后即将引用设为null
            var lChild=array[temp.lChild] 
            temp.lChild=null
            stack.pop()
            stack.push(temp)
            stack.push(lChild)
        }else if(temp.rChild!==null){
            //遍历后即将引用设为null
            var rChild=array[temp.rChild]
            temp.rChild=null
            stack.pop()
            stack.push(temp)
            stack.push(rChild)
        }else{
            console.log(temp.data)
            stack.pop()
        }
         
    }

}

var array=BinaryTree()
PostOrder(array[0])

输出 d b f e c a

数据结构算法实现-二叉树遍历的非递归算法

标签:递归   16px   数据结构   树遍历   使用   return   堆栈   div   算法   

原文地址:http://www.cnblogs.com/heinz-lxy/p/6680532.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!