二叉树是什么?
- 树中每个节点最多只能有两个子节点
- 在js中通常用Object来模拟二叉树
//js二叉树的基本格式
const binaryTree=[
val:1,
left:{
val:2,
left:null,
right:null
},
right:{
val:3,
left:null,
right:null
}
]
//我们写一个多节点demo的后续计算
const bt = {
val:1,
left:{
val:2,
left:{
val:4,
left:null,
right:null,
},
right:{
val:5,
left:null,
right:null
}
},
right:{
val:3,
left:{
val:6,
left:null,
right:null,
},
right:{
val:7,
left:null,
right:null
}
}
}
先序遍历算法口诀
1、访问根节点
2、对根节点的左子树进行先序遍历
3、对根节点的右子树进行先序遍历
const preorder = (root) =>{
if(!root){return}
console.log(root.val);
preorder(root.left)
preorder(root.right)
}
preorder(bt)//1,2,4,5,3,6,7
//非递归版,
const preorder = (root) =>{
if(!root){return}
const stack = [root];
while(stack.length){
const n = stack.pop();
console.log(n.val)
if(n.right){
stack.push(n.right)
}
if(n.left){
stack.push(n.left)
}
}
}
preorder(bt)//1,2,4,5,3,6,7
中序遍历算法口诀
- 对根节点的左子树进行中序遍历
- 访问根节点
- 对根节点的右子树进行中序遍历
const inorder = (root) =>{
if(!root){return}
inorder(root.left)
console.log(root.val);
inorder(root.right)
}
inorder(bt)//4,2,5,1,6,3,7
//非递归版
const inorder = (root) =>{
if(!root){return}
const stack = [];
let p = root;
while(stack.length||p){
while(p){
stack.push(p)
p = p.left;
}
const n = stack.pop();
console.log(n.val)
p = n.right;
}
}
inorder(bt)//4,2,5,1,6,3,7
后序遍历
- 对根节点的左子树进行后序遍历
- 对根节点的右子树进行后序遍历
- 访问根节点
const postorder = (root) =>{
if(!root){return}
postorder(root.left)
postorder(root.right)
console.log(root.val);
}
postorder(bt)//4,5,2,6,7,3,1
//非递归版
const postorder = (root) =>{
if(!root){return}
const stack = [root];
const outputStack = [];
while(stack.length){
const n = stack.pop();
outputStack.push(n)
if(n.left){
stack.push(n.left)
}
if(n.right){
stack.push(n.right)
}
}
while(outputStack.length){
const n = outputStack.pop();
console.log(n.val)
}
}
postorder(bt)//4,5,2,6,7,3,1