js树操作,层级遍历,先序序列化与反序列化
class TreeNode {
/**
* 树节点
* @param value
*/
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class Tree {
constructor(rootNode) {
this.rootNode = rootNode;
}
/**
* 树的层级遍历,包括打印层号
*/
layerIterator() {
let queue = [this.rootNode];
let layer = 1;
let layerLast = this.rootNode;
let layerLine = 'layer: 1, value: ';
while (queue.length) {
let last = queue.shift();
layerLine += last.value + ', ';
last.left && queue.push(last.left);
last.right && queue.push(last.right);
if (last === layerLast) {
console.log(layerLine.substring(0, layerLine.length - 2));
if (!queue.length) {
break;
}
layer++;
layerLine = `layer: ${layer}, value: `;
layerLast = queue[queue.length - 1];
}
}
}
/**
* 先序遍历树,并将树序列化为字符串
* @returns {string}
*/
preorderTraversal() {
let result = [];
Tree.preorderTraversalImpl(this.rootNode, result);
return result.join('!');
}
static preorderTraversalImpl(treeNode, result) {
result.push(treeNode.value);
if (treeNode.left) {
this.preorderTraversalImpl(treeNode.left, result);
} else {
result.push('#');
}
if (treeNode.right) {
this.preorderTraversalImpl(treeNode.right, result);
} else {
result.push('#');
}
}
/**
* 先序字符串反序列化为树
* @param treeString
* @returns {TreeNode} 树的根节点
*/
static preorderStringToTree(treeString) {
let queue = treeString.split('!');
let rootNode = new TreeNode(queue.shift());
let currentNode = rootNode;
let queueNode = [rootNode];
let isLeft = true;
while (queue.length) {
let currentValue = queue.shift();
if (currentValue !== '#') {
let createNode = new TreeNode(currentValue);
if (isLeft) {
currentNode.left = createNode;
} else {
currentNode.right = createNode;
}
queueNode.unshift(createNode);
currentNode = createNode;
isLeft = true;
} else {
currentNode = queueNode.shift();
isLeft = false;
}
}
return rootNode;
}
}
let node1 = new TreeNode(1);
let node2 = new TreeNode(2);
let node3 = new TreeNode(3);
node1.left = node2;
node1.right = node3;
let node4 = new TreeNode(4);
let node5 = new TreeNode(5);
let node6 = new TreeNode(6);
node2.left = node4;
node3.left = node5;
node3.right = node6;
let node7 = new TreeNode(7);
let node8 = new TreeNode(8);
node5.left = node7;
node5.right = node8;
let tree = new Tree(node1);
//树的层级遍历
tree.layerIterator();
//先序遍历树,并序列化为字符串
let result = tree.preorderTraversal();
console.log(result);
//反序列化,先序遍历树字符串
let rootNode = Tree.preorderStringToTree(result);
console.log(rootNode);
let tree2 = new Tree(rootNode);
console.log(tree2.layerIterator());
树结构如下: