Thread: Function to determine if a tree is sorted (i.e. BST)

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Quote Originally Posted by anduril462 View Post
    I find the "GAP" version stupid. It uses unnecessary paramaters and variables that just confuse things.
    That's what I am saying!

    I think something like this should work:

    Code:
    int fun(Treeptr p, int * ap, int * bp) {
      int a, b;
      if (p->left == NULL && p->right == NULL) {
        *ap = p->value;
        return 1;
      }
      if (p->right == NULL) {
        *bp = p->value;
        return (fun(p->left, &b, ap) && p->value > b);
      }
      if (p->left == NULL) {
        *ap = p->value;
        return (fun(p->right, &a, bp) && p->value < a);
      }
      return (fun(p->right, &a, bp) && fun(p->left, &b, ap));
    }
    However, the code I provided above for the treemanagement.c seems to fail to build a BST, or maybe the printing is not accurate, so I am testing it further in paper. Thanks anduril462.

    If someone can verify that the above is correct or not, (s)he is welcomed.

    [EDIT]
    It appears that the printing was done horizontally and not vertically. So I could test the function and it seems OK.
    Last edited by std10093; 10-03-2014 at 08:08 AM.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorted binary tree
    By std10093 in forum C Programming
    Replies: 6
    Last Post: 08-29-2014, 10:07 AM
  2. determine if tree is strictly binary bst
    By ashir30000 in forum C++ Programming
    Replies: 3
    Last Post: 02-25-2010, 01:51 PM
  3. Inserting value to a sorted binary tree?
    By HappySmileMan in forum C Programming
    Replies: 3
    Last Post: 02-15-2009, 09:34 AM
  4. Function to Determine if Int is Prime
    By Adrian in forum C Programming
    Replies: 7
    Last Post: 11-22-2007, 08:21 AM
  5. Building a Binary Search Tree off sorted data
    By BlackCitan in forum C Programming
    Replies: 0
    Last Post: 12-01-2003, 09:52 PM