收集樹中的節點,放在一個map中去。key是高度,個數是寬度。
使用前序遍歷,初始樹的高度爲1,當節點不空時高度加一,當節點空減一,把葉結點遍歷完後減一。
二叉樹
function createNode(data) {
return {
data: data||null,
left: null,
right:null
}
}
var tree = {
data: 1,
left: {
data: 2,
left: {
data:3
},
right:{
data:5,
left: {
data:8
}
}
},
right: {
data: 4,
left: {
data: 5
},
right: {
data: 15
}
}
};
var height=0;
var map={};
rec(tree);
function rec(node) {
if (node) {
if(!map[height]){
map[height]=[];
}
map[height].push(node);
}else{
height--;
return;
}
if (node.left) {
height++
rec(node.left);
}
if (node.right) {
height++
rec(node.right);
}
height--;
}
多個子元素
function createNode(data) {
return {
data: data||null,
left: null,
right:null
}
}
var tree = {
data: 1,
child:[
{
data:2,
child:[
{
data:3,
child:[]
},
{
data:4,
child:[
{
data:6,
child:[]
}
]
}]
}
]
};
var height=0;
var map={};
rec(tree);
function rec(node) {
if (node) {
if(!map[height]){
map[height]=[];
}
map[height].push(node);
}else{
height--;
return;
}
if (node.child && node.child.length) {
for (var i = 0; i < node.child.length;i++){
height++
rec(node.child[i]);
}
}
height--;
}