简体   繁体   中英

Leaf nodes from Preorder of a Binary Search Tree

Given a Preorder traversal of a Binary Search Tree. The task is to print leaf nodes of the Binary Search Tree from the given preorder.

Example:

Input: 67 34 12 45 38 60 80 78 79 95 100

Output: 12 38 60 79 100

Following is the recursive solution I came up with but not getting the correct output

Can anyone help me understand what I am doing wrong?

#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);
}

Typo is here:

 for(int i = low; i<=high; i++) //finds the right node. ...
   {
       if(root < preorder[i]);//<-----  
                             ^
       ...  

Causing the following lines to be executed regarless:

   right = i;                               // stores the index of right node
   break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM