}
}
let charecters= [1,2,3,4,5,6];
let node = new Node();
node.text = charecters[0];
buildTree(node, 0);
console.log(node);
- 非递归
//非递归创建树
function createBinaryTree() {
var len = charecters.length, //数组的长度
index = 0, //索引从0开始
nodes = new Array(); //创建一个临时数组,用于存放二叉树节点
//循环创建二叉树节点存放到数组中
for (var i = 0 ; i < charecters.length ; i++) {
var node = new Node();
node.text = charecters[i];
nodes.push(node);
}
//循环建立二叉树子节点的引用
while(index < len) {
var leftIndex = 2*index+1, //当前节点左孩子索引
rightIndex = 2*index+2; //当前节点右孩子索引
//给当前节点添加左孩子
nodes[index].leftChild = nodes[leftIndex];
//给当前节点添加右孩子
nodes[index].rightChild = nodes[rightIndex];
index++;
}
root = nodes[0];
}
let charecters= [1,2,3,4,5,6];
var root;
createBinaryTree();
console.log(“非递归”, root);
-
递归
-
非递归
- 递归
//中序遍历
function secondIteration(node) {
//访问左节点
if(node.leftChild) {
if(node.leftChild.leftChild) {
secondIteration(node.leftChild);
}
else {
strText += node.leftChild.text;
}
}
//访问根节点
strText += node.text;
//访问右节点
if(node.rightChild) {
if(node.rightChild.leftChild) {
secondIteration(node.rightChild);
}
else {
strText += node.rightChild.text;
}
}
}
let charecters= [1,2,3,4,5,6];
let node = new Node();
node.text = charecters[0];
//先使用递归构建树
buildTree(node, 0);
//中序遍历
var strText = “”;
secondIteration(node)
console.log(“中序”, strText);
- 非递归
//中序非递归
function notSecondIteration() {
var resultText = ‘’,
stack = new Stack();
stack.push(node);
while(!stack.isEmpty()) {
//从根节点一直往下找左孩子节点直到最后一个左孩子节点,然后保存在栈中
while(node.leftChild) {
node = node.leftChild;
stack.push(node);
}
//弹出栈
var tempNode = stack.pop();
//访问临时节点
resultText += tempNode.text;
if(tempNode.rightChild) {
node = tempNode.rightChild;
stack.push(node);
}
}
return resultText;
}
let charecters= [1,2,3,4,5,6];
let node = new Node();
node.text = charecters[0];
//先使用递归构建树
结束
一次完整的面试流程就是这样啦,小编综合了腾讯的面试题做了一份前端面试题PDF文档,里面有面试题的详细解析,分享给小伙伴们,有没有需要的小伙伴们都去领取!