本文已参与「新人创作礼」活动,一起开启掘金创作之路
本文主要记录了用JavaScript实现数据结构 -- 树、二叉树,以及二叉树的前、中、后序遍历。
二叉树
每个节点最多有两个子节点的树叫二叉树。
二叉树的常用操作
定义二叉树
//定义二叉树
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
}
}
}
前序遍历
前序遍历过程
根 => 左 => 右
- 访问根节点;
- 对根节点的左子树进行前序遍历;
- 对根节点的右子树进行前序遍历;
代码实现
用递归实现前序遍历:
//前序遍历
const preorder = (root) => {
if(!root){
return ;
}
console.log(root.val);
preorder(root.left);
preorder(root.right);
}
preorder(bt);
用栈实现前序遍历:
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);
中序遍历
中序遍历过程
左 =>根 => 右
- 对根节点的左子树进行前序遍历;
- 访问根节点;
- 对根节点的右子树进行前序遍历;
代码实现
用递归实现中序遍历:
const inorder = (root) => {
if(!root){
return ;
}
inorder(root.left);
console.log(root.val);
inorder(root.right);
}
inorder(bt);
用栈实现中序遍历:
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);
后序遍历
后序遍历过程
左 => 右 => 根
-
对根节点的左子树进行前序遍历;
-
对根节点的右子树进行前序遍历;
-
访问根节点;
代码实现
用递归实现后序遍历:
const postorder = (root) => {
if(!root){
return ;
}
postorder(root.left);
postorder(root.right);
console.log(root.val);
}
postorder(bt);
用栈实现后序遍历:
const postorder = (root) => {
if(!root){
return ;
}
const outputstack = [];
const stack = [root];
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);
本文到此结束
如果大家还有什么其他想法,欢迎在评论区交流!