作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试编写一个函数来打印从根节点到叶节点的所有路径。
例如;
printPaths(bt1);
>2_1_
>2_3_
对于这个例子,2 是根,1-3 是叶。
这是我的简单代码,我找不到换行的地方,因为当我在任何地方写 printf("\n")
时,它都会打印疯狂的输出,所以我找不到问题所在这段代码。
void printPaths(TreeNode* root) {
if(root != NULL) {
printf("%d ", root->val);
printPaths(root->left);
printPaths(root->right);
}
}
最佳答案
你需要在“每条路径的末尾”换行,所以当你到达一片叶子时:
if (root->left == NULL && root->right == NULL)
printf("\n");
但是,您将无法使用代码再次打印整个路径,您需要在访问树时跟踪路径并在到达叶子时打印路径:
void printPaths(TreeNode* root, int path[], int len)
{
if (root == NULL) // if the root is NULL, do not print anything
return;
path[len++] = root->val; // add root to your path
if (root->left == NULL && root->right == NULL) // we reached a leaf
printPath(path, len); // print the path we followed to reach this leaf
else
{
printPaths(root->left, path, len);
printPaths(root->right, path, len);
}
}
void printPath(int path[], int len)
{
for (int i = 0; i < len; i++)
printf("%d ", path[i]);
printf("\n");
}
关于c - 如何在 C 中实现打印树的所有路径的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37483690/
我是一名优秀的程序员,十分优秀!