Wednesday, May 11, 2011

Print binary search tree in increasing order

Given a binary search tree (aka an "ordered binary tree"), iterate over the nodes to print them out in increasing order. So the tree...
       4
      / \
     2   5
    / \
   1   3
Produces the output "1 2 3 4 5". This is known as an "inorder" traversal of the tree.
Hint: For each node, the strategy is: recur left, print the node data, recur right.

Here is code in c/cpp:

void printTree(struct node* node) {
/*
 Given a binary search tree, print out
 its data elements in increasing
 sorted order.
*/
void printTree(struct node* node) {
  if (node == NULL) return;   printTree(node->left);
  printf("%d ", node->data);
  printTree(node->right);
}
 

1 comment:

  1. Very good information indeed. Thanks for posting this here. You can find more information on Binary search tree (BST) here in the following link with examples.

    Binary search tree (BST) in Cpp with examples

    ReplyDelete