Binary tree traversal

From CodeCodex

The code below allows you to traverse a binary search tree in order.

Implementations[edit]

Java[edit]

This code assumes you have a Node object that has the properties left and right. It will display the key of each node in order, from left to right.

void display(){
  System.out.print(lnr(root));
}

void lnr(Node p){
  if(p null) return;
  lnr(p.left);
  System.out.print(p.key);
  lnr(p.right);
}

C[edit]

Here is the node:

struct tree_node {
    tree_node *left;   // left subtree has smaller elements
    tree_node *right;  // right subtree has larger elements
    int data;
};

This recursive code will print out the nodes in order from left to right.

void print_inorder(tree_node *p) {
    if (p != NULL) {
        print_inorder(p->left);  // print left subtree
        cout << p->data << endl; // print this node
        print_inorder(p->right); // print right subtree
    }
}