C# Binary Tree's - Inorder/Preorder and PostOrder (Recursion Help)
Inorder is very similar to what you already have, just move your code around a little bit in where you are handling the current node:
public void recursiveInorder(BinaryTreeNode root)
{
if (root.Left != null)
{
recursiveInorder(root.Left);
}
Console.Write(root.Data.ToString());
if (root.Right != null)
{
recursiveInorder(root.Right);
}
}
The difference to preorder is just that you first traverse the left subtree, then process the current node and finally traverse the right subtree.
The wiki page for tree traversal states:
Binary Tree
To traverse a non-empty binary tree in preorder, perform the following operations recursively at each node, starting with the root node:
- Visit the root.
- Traverse the left subtree.
- Traverse the right subtree.
To traverse a non-empty binary tree in inorder (symmetric), perform the following operations recursively at each node:
- Traverse the left subtree.
- Visit the root.
- Traverse the right subtree.
To traverse a non-empty binary tree in postorder, perform the following operations recursively at each node:
- Traverse the left subtree.
- Traverse the right subtree.
- Visit the root.
[BTW, it was the first search hit.]