示例数据
var btree = {
value:"A",
leftLeaf:{
value:"B",
leftLeaf:{
value:"D",
leftLeaf:null,
rightLeaf:null
},
rightLeaf:{
value:"E",
leftLeaf:null,
rightLeaf:null
}
},
rightLeaf:{
value:"C",
leftLeaf:{
value:"F",
leftLeaf:null,
rightLeaf:null
},
rightLeaf:{
value:"G",
leftLeaf:null,
rightLeaf:null
}
}
}
先序遍历(递归):
function preorder(root){ //递归方式
if(!root) return;
console.log(root.value);
preorder(root.leftLeaf); //递归调用
preorder(root.rightLeaf); //递归调用
}
preorder(btree); //ABDECFG
先序遍历(非递归):利用栈后进先出的特点来处理
function preorder(root){
if(!root) return;
let stack = [root];
while(stack.length>0){
let node = stack.pop();
console.log(node.value);
if(node.rightLeaf){
stack.push(node.rightLeaf);
}
if(node.leftLeaf){
stack.push(node.leftLeaf);
}
}
}
preorder(btree); //ABDECFG
中序遍历(递归):
function midorder(root){ //递归方式
if(!root) return;
midorder(root.leftLeaf); //递归调用
console.log(root.value);
midorder(root.rightLeaf); //递归调用
}
preorder(btree); //DBEAFCG
中序遍历(非递归):利用栈和指针
function midorder(root){
if(!root){
return;
}
let p = root; //将二叉树的所有左节点入栈
while(p || stack.length){
while(p){
stack.push(p);
p = p.leftLeaf;
}
const node = stack.pop(); //弹出最左的节点输出
console.log(node.value);
p = node.rigtLeaf; //将栈顶元素的右节点当做root,重复上边的步骤
}
}
midorder(tree); //DBEAFCG
后序遍历(递归):
function postorder(root){ //递归方式
if(!root) return;
postorder(root.leftLeaf); //递归调用
postorder(root.rightLeaf); //递归调用
console.log(root.value);
}
preorder(btree); //DEBFGCA
后序遍历(非递归):
function postorder(root){
if(!root){return}
const stack = [root];
const outputStack = [];
while(stack.length){
const node = stack.pop();
outpusStack.push(node);
if(node.leftLeaf) stack.push(node.leftLeaf);
if(node.rightLeaf) stack.push(node.rightLeaf);
}
while(outputStack.length){
const outNode = pop();
console.log(outNode.value)
}
}
postorder(tree); //DEBFGCA