如何解决二叉搜索树预序的叶节点
给定二叉搜索树的先序遍历。任务是从给定的预序打印二叉搜索树的叶节点。
示例:
输入: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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。