#java #algorithm #return #nodes #leaf
Вопрос:
ALGORITHM LeafCounter(BTNode node)
// Computers recursively the number of leaves in a binary tree
// Input: Root node of a binary (sub-)tree 1/
// Output: The number of leaves in the tree rooted by input node
if (node == null) return 0;
else
return LeafCounter(node.getLeftChild 0 ) Leaf Counter(node.getRightChild();
Я не уверен, как это отредактировать, чтобы он точно подсчитывал листья? Кроме того, если бы вы могли предоставить доказательства того, почему это не удается, это было бы очень полезно для меня, похоже, это должно работать
Ответ №1:
Правильный Алгоритм:
ALGORITHM LeafCounter(BTNode node)
// Computers recursively the number of leaves in a binary tree
// Input: Root node of a binary (sub-)tree 1/
// Output: The number of leaves in the tree rooted by input node
if (node == null) return 0;
else
//Since current node is not null so
return 1 LeafCounter(node.getLeftChild()) Leaf Counter(node.getRightChild());
Примечание. Возможно, вам потребуется вычесть 1 из конечного результата, чтобы исключить корневой узел из подсчета.
Ответ №2:
Вам просто нужно проверить состояние листьев, чтобы получить правильные результаты.
ALGORITHM LeafCounter(BTNode node)
// check base condition
if (node == null) return 0;
// check leaf condition
if (node.getLeftChild() == null amp;amp; node.getRightChild() == null) return 1;
// recurse for children
else return LeafCounter(node.getLeftChild()) LeafCounter(node.getRightChild());