返回
前端开发速查表:JavaScript树操作方法全汇集
前端
2023-09-13 08:13:45
在前端开发中,树结构的数据操作是一个必备技能。树结构是一种常见的数据结构,在实际的业务开发中,我们也会遇到许多树结构的。掌握树的操作方法,可以帮助我们更轻松地处理这些数据。
本文整理了一系列的关于JavaScript树的操作方法,拿来即用~
1. 树的遍历
1.1 前序遍历
function preOrderTraversal(root) {
if (root === null) {
return;
}
console.log(root.value);
preOrderTraversal(root.left);
preOrderTraversal(root.right);
}
1.2 中序遍历
function inOrderTraversal(root) {
if (root === null) {
return;
}
inOrderTraversal(root.left);
console.log(root.value);
inOrderTraversal(root.right);
}
1.3 后序遍历
function postOrderTraversal(root) {
if (root === null) {
return;
}
postOrderTraversal(root.left);
postOrderTraversal(root.right);
console.log(root.value);
}
2. 树的插入
function insert(root, value) {
if (root === null) {
return new Node(value);
}
if (value < root.value) {
root.left = insert(root.left, value);
} else {
root.right = insert(root.right, value);
}
return root;
}
3. 树的删除
function deleteNode(root, value) {
if (root === null) {
return null;
}
if (value < root.value) {
root.left = deleteNode(root.left, value);
} else if (value > root.value) {
root.right = deleteNode(root.right, value);
} else {
if (root.left === null) {
return root.right;
} else if (root.right === null) {
return root.left;
}
const minNode = findMinNode(root.right);
root.value = minNode.value;
root.right = deleteNode(root.right, minNode.value);
}
return root;
}
4. 树的查找
function find(root, value) {
if (root === null) {
return null;
}
if (value === root.value) {
return root;
} else if (value < root.value) {
return find(root.left, value);
} else {
return find(root.right, value);
}
}
5. 树的高度
function height(root) {
if (root === null) {
return 0;
}
const leftHeight = height(root.left);
const rightHeight = height(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
6. 树的宽度
function width(root) {
if (root === null) {
return 0;
}
const queue = [root];
let maxWidth = 0;
while (queue.length > 0) {
const levelSize = queue.length;
maxWidth = Math.max(maxWidth, levelSize);
for (let i = 0; i < levelSize; i++) {
const node = queue.shift();
if (node.left !== null) {
queue.push(node.left);
}
if (node.right !== null) {
queue.push(node.right);
}
}
}
return maxWidth;
}