题目是给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
解决这个问题,首先先写一个二叉树的对象,题目中给了
Definition for a binary tree node.
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
Definition for singly-linked list.
function ListNode(val!=undefind) {
this.val = val;
this.next = null;
}
我想了一下,如果想要遍历二叉树,还想知道深度是多少,我能想到最简单的方法就是加个index 然后判断index是几 深度就是几
Definition for a binary tree node.
function TreeNode(val) {
this.val = val;
this.index = null
this.left = this.right = null;
}
Definition for singly-linked list.
function ListNode(val!=undefind) {
this.val = val;
this.next = null;
}
设置好后,我们添加一个方法来遍历传入的树的值
TreeNode.prototype.toString=function(o,index){
this.index = index
o[this.index] = o[this.index]==undefined?undefined:o[this.index]
o[this.index+1] = o[this.index+1]==undefined?undefined:o[this.index+1]
if(this.right!=null){
this.right.toString(o,index+1)
}
if(this.left!=null){
this.left.toString(o,index+1)
}
if(o[this.index]!=undefined){
let oee = new ListNode(this.val)
oee.next = o[this.index]
o[this.index]= oee
}else{
o[this.index] = new ListNode(this.val)
}
}
这里我对深度设置为首次传入的为0 根据进入left 或者right的次数累加,o是用来收集我们每个不同深度的树新生成的对象的
总体代码为下
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.index = 0
* this.left = this.right = null;
* }
*/
/**
* Definition for singly-linked list.
* function ListNode(val!=undefind) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {TreeNode} tree
* @return {ListNode[]}
*/
TreeNode.prototype.toString=function(o,index){
this.index = index
o[this.index] = o[this.index]==undefined?undefined:o[this.index]
o[this.index+1] = o[this.index+1]==undefined?undefined:o[this.index+1]
if(this.right!=null){
this.right.toString(o,index+1)
}
if(this.left!=null){
this.left.toString(o,index+1)
}
if(o[this.index]!=undefined){
let oee = new ListNode(this.val)
oee.next = o[this.index]
o[this.index]= oee
}else{
o[this.index] = new ListNode(this.val)
}
}
var listOfDepth = function(tree) {
let p = []
tree.toString(p,0)
p=p.filter(val=>val!=undefined)
return p
};
只能说效率一般,如果各位大佬有更好的办法,请给予指正,谢谢各位