有没有办法让我逐层打印二叉树,同时每次有空节点时显示 NULL?
例如,假设我们有 this tree :
输出应如下所示:
A
B C
D NULL E F
我应该如何编写代码来用树生成所述输出?提前致谢。这是我在此的头一篇博文。抱歉,如果格式和语法已关闭。
最佳答案
这里暴露的想法和算法概念比你应用的技术更重要。话虽这么说:
C++ 答案(轻松移植到 C#):
假设一个与此类似的经典二叉树结构:
struct node {
char data;
node* left;
node* right;
}
// Function to print each level in the tree*
void printByLevel(node* root) { // Copy root node, pass by value.
int height = height(root); // Get tree height. Total amount of levels to print.
for (int i = 1; i <= h; i++) {
printLevel(root, i);
std::cout << std::endl; // A line after each level is printed.
}
}
您将需要下面的辅助函数,以及计算树高的函数才能执行上面的函数。
// Print nodes at ONE specific level
void printLevel(node* root, int level) { // Copy root node, pass by value.
if (root != nullptr) {
if (level == 1)
std::cout << root->data << ' ';
else if (level > 1) {
printLevel(root->left, level-1);
printLevel(root->right, level-1);
}
}
std::cout << "NULL" << ' '; // No value, print "NULL"
}
关于c# - 打印具有空节点的二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43106251/