给定二叉搜索树的预序遍历。任务是从给定的预订单中打印二叉搜索树的叶节点。
的例子:
输入:67 34 12 45 38 60 80 78 79 95 100
输出:12 38 60 79 100
下面是我提出的递归解决方案,但没有得到正确的输出
谁能帮我理解我做错了什么?
#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);
}
这里有错字:
for(int i = low; i<=high; i++) //finds the right node. ...
{
if(root < preorder[i]);//<-----
^
...
导致以下行无论如何都被执行:
right = i; // stores the index of right node
break;