非递归先序遍历
/**
* 先序遍历(非递归)
* 方法:手动压栈(先压右子节点,后压左子节点)
*/
preorderPrintTreeUnRecur(head:TNode){
let stack = [];
stack.push(head);
while(stack.length != 0){
let top = stack.pop(); //1.从栈中弹出一个节点
console.log(top.value); //2.打印
if(top.right) stack.push(top.right); //如果有 它的右子节点压栈
if(top.left) stack.push(top.left); //如果有 它的左子节点压栈
}
}
非递归中序遍历
/**
* 中序遍历(非递归)
* 1.检查head节点是否有左子节点时,如果有,将其所有左边界挨个压入栈中
* 2.head的左边界压栈完毕后,栈顶弹出一个节点,打印。
* 3.检查该节点是否有右子节点,如果有,压入栈中,并且将head设为它。
* 4.重复上述操作。
*/
middlePrintTreeUnRecur(head:TNode){
let stack = [];
stack.push(head);
while(stack.length != 0){
if(head.left != null){ //检查head节点是否有左子节点时,如果有,将其所有左边界都压入栈中
stack.push(head.left);
head = head.left;
}else{
let top = stack.pop();
console.log(top.value);
if(top.right){
stack.push(top.right);
head = top.right;
}
}
}
}
非递归后序遍历
/**
* 后序遍历(非递归)
*方法:额外需要一个辅助栈
*/
lastPrintTreeUnRecur(head: TNode) {
let stack = [];
let hStack = [];
stack.push(head);
while(stack.length != 0){
let top = stack.pop();//1.从栈中弹出一个节点
hStack.push(top);//2.放入辅助栈中
if(top.left) stack.push(top.left); //如果有 它的左子节点压栈
if(top.right) stack.push(top.right); //如果有 它的右子节点压栈
}
while(hStack.length != 0){ //将辅助栈中的节点挨个弹出即可
let top = hStack.pop();
console.log(top.value);
}
}