C 二叉搜索树前序的叶节点
给定二叉搜索树的前序遍历。任务是从给定的前序打印二叉搜索树的叶节点 例如: 输入:67 34 12 45 38 60 80 78 95 100 产出:12386079100 下面是我提出的递归解决方案,但没有得到正确的输出 谁能帮我理解我做错了什么C 二叉搜索树前序的叶节点,c,data-structures,binary-search-tree,C,Data Structures,Binary Search Tree,给定二叉搜索树的前序遍历。任务是从给定的前序打印二叉搜索树的叶节点 例如: 输入:67 34 12 45 38 60 80 78 95 100 产出:12386079100 下面是我提出的递归解决方案,但没有得到正确的输出 谁能帮我理解我做错了什么 #include<stdio.h> #define MAX 100 int preorder[MAX], n; void leaf(int low,int high) // prints leaf nodes from
#include<stdio.h>
#define MAX 100
int preorder[MAX], n;
void leaf(int low,int high) // prints leaf nodes from preorder
{
if(high <= low) // base condition: print the leaf and return
{
printf("%d ", preorder[low]);
return;
}
int root = preorder[low]; //stores the value of root node;
int left =root > preorder[low+1]? low+1: low ; // stores the index of left node, if left subtree ie empty sets left = low
int right = low; //stores the index of right node. Initialized to low
for(int i = low; i<=high; i++) //finds the right node. i.e. first node larger than root(between low and high)
{
if(root < preorder[i]);
{
right = i; // stores the index of right node
break;
}
}
if(left != low) //if left = low, then left subtree is empty
leaf(left, right-1); //recurse on the left subtree
if(right != low) //if right = low, then right subtree is empty
leaf(right,high); //recurse on the right subtree
}
int main()
{
printf("Enter size of input: ");
scanf("%d",&n);
printf("Enter input:");
for(int i = 0; i<n; i++)
{
scanf("%d",&preorder[i]);
}
leaf(0,n-1);
}
#包括
#定义最大值100
int预序[MAX],n;
void leaf(int-low,int-high)//从预订单打印叶节点
{
if(high preorder[low+1]?low+1:low;//存储左节点的索引,如果左子树为空,则设置left=low
int right=low;//存储右节点的索引。初始化为low
对于(inti=low;i输入错误,请参见:
for(int i = low; i<=high; i++) //finds the right node. ...
{
if(root < preorder[i]);//<-----
^
...
出于某种原因,我的编译器抛出了一个警告,表示i++
将永远不会在语句中执行:For(int i=low;i您有一个简单的输入错误:if(root
有一个多余的分号:if
正文为空,下面的代码块将无条件执行。如果您的问题得到解决,为什么不呢?这只是一个打字错误,不能保证完整的答案。(好吧,我收回我的话。改为接受rykker的答案。)是的,我以为你是OP。分号明显比名字好。:(
)。
right = i; // stores the index of right node
break;