一周一个js测试题01
需求: 给定一个根节点let root = new Node(0, null, null)
- 编写一个createTree(root, n)方法根据传入的n生成一个有n层二叉树,叶子节点的值为其所在的层数
- 写一个printTree(root)方法将该二叉树打印出来
function Node(val, left, right) { this.val = val this.left = left this.right = right } let root = new Node(0, null, null) let n = 3 createTree(root, n) printTree(root) // [[0], [1, 1], [2, 2, 2, 2], [3, 3, 3, 3, 3, 3, 3, 3]]
手动思考两分钟~
手动思考两分钟~
手动思考两分钟~
手动思考两分钟~
手动思考两分钟~
手动思考两分钟~
// createTree
function createTree(root, n) {
// 因为每一个节点的val值为其所在层的层数 所以以val值作为是否到达第n层的标识
// 当root.val值大于n时即退出
if (root.val + 1 > n) {
return
}
// 为left和right赋值 其val值即为root.val+1
root.left = new Node(root.val+1, null, null)
root.right = new Node(root.val+1, null, null)
// 递归生成树的叶子节点 层级减1
createTree(root.left, level)
createTree(root.right, level)
}
// printTree(root)
function printTree(root) {
// 因为其打印的值是一个数组 所以这里我们需要一个数组来存储遍历出来的值
let items = []
// 这里因为我需要递归遍历又不能影响items 所以来一个内部函数
function inner(child) {
if (child) {
const val = child.val
// 如果items[val]是一个数组则向其中下标为val的数组加入一个val
items[val] instanceof Array ? items[val].push(val) : items[val] = [val]
// 递归遍历其叶子节点
inner(child.right)
inner(child.left)
}
}
inner(root.right)
inner(root.left)
// 输出items的值
console.log(items)
}
晚上睡觉的时候回味起来,上面那个方法时巧借了其node的val值,若是val值不为其索引那岂不是要失效了,所以今天补上广度优先遍历的方法,在遍历的时候手动给每一个node添加一个index索引即可,以下是实现的具体方法,对于此题,个人认为下面这种遍历方法更加可取
// 广度优先遍历
function printTree(root) {
// 用来存放最后结果的数组
let items = []
// 该数组用来模拟队列
let queue = []
queue.push({
index: 0, // 在items数组中的索引标识
node: root
})
let next = queue.shift()
while (next.node) {
// 将next中的val值根据index放入items中
let {index, node} = next
items[index] ? items[index].push(node.val) : items[index] = [node.val]
// 将next.node的左右节点放入队列之中
queue.push({
index: index + 1,
node: node.left
})
queue.push({
index: index + 1,
node: node.right
})
next = queue.shift() // 将next赋值为队列中的第一个值继续循环
}
console.log(items)
}
// 测试
let root = new Node(0, null, null)
buildTree(root, 4)
printTree(root)
以上皆是个人想法,期待更优的解法