假设这样一棵树,
4
2 6
1 3 5 7
和对象文本
tree = {
data: 4,
left: {
data: 2,
left: {
data: 1,
left: null,
right: null
},
right: {
data: 3,
left: null,
right: null
}
},
right: {
data: 6,
left: {
data: 5,
left: null,
right: null
},
right: {
data: 7,
left: null,
right: null
}
}
};
你可以递归调用函数并获得第一左部分,然后树的右边部分。该算法被称为depth-first search。
该函数使用单个检查,因为这足以先检查然后继续前进。
var depthFirth = function (node) {
if (node) {
console.log(node.data);
depthFirth(node.left);
depthFirth(node.right)
}
},
tree = { data: 4, left: { data: 2, left: { data: 1, left: null, right: null }, right: { data: 3, left: null, right: null } }, right: { data: 6, left: { data: 5, left: null, right: null }, right: { data: 7, left: null, right: null } } };
depthFirth(tree); // 4 2 1 3 6 5 7
对于breadth-first search,一种算法,该算法首先遍历树的每一个级别,你可以如上使用此代码与同一棵树上的数据。
var breadthFirst = function (node) {
function bf(queue) {
var newQueue = [];
queue.forEach(function (node) {
console.log(node.data);
node.left && newQueue.push(node.left);
node.right && newQueue.push(node.right);
});
newQueue.length && bf(newQueue);
}
bf([node]);
},
tree = { data: 4, left: { data: 2, left: { data: 1, left: null, right: null }, right: { data: 3, left: null, right: null } }, right: { data: 6, left: { data: 5, left: null, right: null }, right: { data: 7, left: null, right: null } } };
breadthFirst(tree); // 4 2 6 1 3 5 7
请加树的数据。 –