求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
const binaryTree = {
root: {
key: 1,
left: {
key: 2,
left: { key: 3, left: null, right: null },
right: { key: 4, left: null, right: null },
},
// right: {
// key: 2,
// left: { key: 4, left: null, right: null },
// right: { key: 5, left: null, right: null },
// },
right: {
key: 2,
left: null,
right: null,
},
},
};
##Way1
function run(root) {
let result = [];
function findTree(node, index) {
if (node.left === null && node.right === null) {
result.push(index + 1);
}
if (node.left) findTree(node.left, index + 1);
if (node.right) findTree(node.right, index + 1);
}
if (root) {
findTree(root, 0);
console.log(result);
result.sort();
return result[0];
} else {
return 0;
}
}
##Way2
function run(root) {
let result = 10000;
function findTree(node, index) {
if (node.left === null && node.right === null) {
if (index + 1 < result) result = index + 1;
}
if (node.left) findTree(node.left, index + 1);
if (node.right) findTree(node.right, index + 1);
}
if (root) {
findTree(root, 0);
return result;
} else {
return 0;
}
}
console.log(run(binaryTree.root));
网友评论