您可以递归地遍历每个节点并控制何时打印,这是 javascript 代码片段。
function findBtreeBoundaries(arr, n, leftCount, rightCount) {
n = n || 0;
leftCount = leftCount || 0;
rightCount = rightCount || 0;
var length = arr.length;
var leftChildN = 2*n + 1, rightChildN = 2*n + 2;
if (!arr[n]) {
return;
}
// this is the left side of the tree
if (rightCount === 0) {
console.log(arr[n]);
}
// select left child node
findBtreeBoundaries(arr, leftChildN, leftCount + 1, rightCount);
// this is the bottom side of the tree
if (leftCount !== 0 && rightCount !== 0) {
console.log(arr[n]);
}
// select right child node
findBtreeBoundaries(arr, rightChildN, leftCount, rightCount + 1);
// this is the right side of the tree
if (leftCount === 0 && rightCount !== 0) {
console.log(arr[n]);
}
}
findBtreeBoundaries([100, 50, 150, 24, 57, 130, null, 12, 30, null, 60, null, 132]);