JS二叉树非递归遍历

二叉树的递归遍历很简单就能够实现,二叉树非递归遍历却想不出来?那你能够看看下面的例子。node

一个二叉树的例子

var root = {
val: 1,
left: {算法

val: 2,
left: {
  val: 4,
},
right:{
  val:5
}

},
right: {code

val: 3,
left: {
  val: 6
},
right: {
  val: 7
}

}
}
先实现三种遍历的递归算法以做比较。递归

先序遍历递归算法

function DLR(root){io

if(root!=null){
    console.log(root.val);
    DLR(root.left);
    DLR(root.right);
}

}
DLR(root)//1,2,4,5,3,6,7console

中序遍历递归算法

function LDR(root){function

if(root!=null){
    LDR(root.left);//先遍历到最左边的节点,而后输出
    console.log(root.val);
    LDR(root.right);
}

}
LDR(root)//4,2,5,1,6,3,7二叉树

后序遍历

function LRD(root){遍历

if(node!=null){
    LRD(root.left);
    LRD(root.right);
    console.log(root.val);
}

}
LRD(root)//4,5,2,6,7,3,1while


看完上面的递归遍历,下面对比一下非递归的二叉树遍历。你会发现递归真心简单。

非递归前序遍历

function DLR(root){

var arr=[],res=[];
if(root!=null){
    arr.push(root);
}
while(arr.length!=0){
    var temp=arr.pop();
    res.push(temp.val);
    //这里先放右边再放左边是由于取出来的顺序相反
    if(temp.right!=null){
        arr.push(temp.right);
    }
    if(temp.left!=null){
        arr.push(temp.left);
    }
}
return res;

}

DLR(root)//1,2,4,5,3,6,7

非递归中序遍历

//先把左边的,所有放进arr再输出,处理右边的。
function LDR(root){

var arr=[],res=[];
while(true){
    while(root!=null){
        arr.push(root);
        root=root.left;
    }
    //终止条件:最后树遍历完了天然就结束
    if(arr.length==0){
        break;
    }
    var temp=arr.pop();
    res.push(temp.val);
    root=temp.right;
}
return res;

}
LDR(root)//4,2,5,1,6,3,7

后序遍历

function LRD(root){

var arr=[],res=[];
arr.push(root);
while(arr.length!=0){
    var p=arr.pop();
    res.push(p.val);
    if(p.left!=null){
        arr.push(p.left);
    }
    if(p.right!=null){
        arr.push(p.right);
    }
}
return res.reverse();

}LRD(root)//4,5,2,6,7,3,1