const root = {
val: "A",
left: {
val: "B",
left: {
val: "D"
},
right: {
val: "E"
}
},
right: {
val: "C",
right: {
val: "F"
}
}
};
//深度优先:前 中 后
//递归
function qian(root){
if(!root){return}
console.log(root.val)
qian(root.left)
qian(root.right)
}
function zhong(root){
if(!root){return}
zhong(root.left)
console.log(root.val)
zhong(root.right)
}
function hou(root){
if(!root){return}
hou(root.left)
hou(root.right)
console.log(root.val)
}
//非递归
function QIAN(root){
if(!root){return}
var result=[];
var stack=[root];
while(stack.length!==0){
var top=stack.pop();
if(top.right){
stack.push(top.right);
}
if(top.left){
stack.push(top.left)
}
result.push(top.val)
}
return result;
}
function ZHONG(root){
if(!root){return}
var result=[]
var stack=[]
while(stack.length!==0||root){
while(root){
stack.push(root)
root=root.left
}
root=stack.pop()
result.push(root.val)
root=root.right
}
return result
}
function HOU(root){
if(!root){return}
var result=[]
var stack=[root]
while(stack.length!==0){
var top=stack.pop()
result.unshift(top.val)
if(top.left){
stack.push(top.left)
}
if(top.right){
stack.push(top.right)
}
}
return result
}
//广度优先:层序遍历
function cengxu(root){
if(!root){return}
var queue=[root]
var result=[]
while(queue.length!==0){
var node=queue.shift()
result.push(node.val)
if(node.left){
queue.push(node.left)
}
if(node.right){
queue.push(node.right)
}
}
return result
}
console.log(cengxu(root))
二叉树的遍历
最新推荐文章于 2024-01-27 15:36:29 发布