什么是前序、中序、后序遍历
前序遍历:根在前,从左往右,一棵树的根永远在左子树前面,左子树又永远在右子树前面
中序遍历:根在中,从左往右,一棵树的左子树永远在根前面,根永远在右子树前面
后序遍历:根在后,从左往右,一棵树的左子树永远在右子树前面,右子树永远在根前面
二叉树的前序遍历
Tree.prototype.prevOrder = function () {
let stack = [];//表示栈
let values = [];//values存储的是节点的值
if (!this.root) {
return;
}
stack.push(this.root);//让根节点入栈
while (stack.length > 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 = [];//values存储的是节点的值
if (!this.root) {
return;
}
let currentNode = this.root;
while(currentNode!=null || stack.length>0){
while (currentNode) {
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();
}