5 kyu

Binary Tree Traversal

1,405 of 2,286Ban-Ath

Description:

Given the root node of a binary tree (but not necessarily a binary search tree,) write three functions that will print the tree in pre-order, in-order, and post-order.

A Node has the following properties:

var data; // A number or string.
Node left; // Undefined if there is no left child.
Node right; // Undefined if there is no right child.
data    # A number or a string
left    # A Node, which is None if there is no left child.
right   # A Node, which is None if there is no right child.
The structure of a tree looks like:
data Tree a = Nil | Node (Tree a) a (Tree a)

Pre-order means that we
1.) Visit the root.
2.) Traverse the left subtree (left node.)
3.) Traverse the right subtree (right node.)

In-order means that we
1.) Traverse the left subtree (left node.)
2.) Visit the root.
3.) Traverse the right subtree (right node.)

Post-order means that we
1.) Traverse the left subtree (left node.)
2.) Traverse the right subtree (right node.)
3.) Visit the root.

Let's say we have three nodes.

var a = new Node("A");
var b = new Node("B");
var c = new Node("C");

a.left = b;
a.right = c;
a = Node("A")
b = Node("B")
c = Node("C")
  
a.left = b
a.right = c
a = Node b "A" c
b = Node Nil "B" Nil
c = Node Nil "C" Nil

Then, preOrder(a) should return ["A", "B", C"]
inOrder(a) should return ["B", "A", "C"]
postOrder(a) should return ["B", "C", A"]

What would happen if we did this?

var d = new Node("D");
c.left = d;
d = Node("D")
c.left = d
d = Node Nil "D" Nil
c = Node d "C" Nil

preOrder(a) should return ["A", "B", "C", "D"]
inOrder(a) should return ["B", "A", "D", "C"]
postOrder(a) should return ["B", "D", "C", "A"]

Binary Trees
Trees
Recursion
Data Structures
Algorithms

Stats:

CreatedOct 24, 2013
PublishedOct 24, 2013
Warriors Trained4713
Total Skips641
Total Code Submissions10243
Total Times Completed2286
JavaScript Completions1405
Haskell Completions333
Python Completions565
Total Stars160
% of votes with a positive feedback rating93% of 292
Total "Very Satisfied" Votes260
Total "Somewhat Satisfied" Votes23
Total "Not Satisfied" Votes8
Ad
Contributors
  • Ban-Ath Avatar
  • jhoffner Avatar
  • ZidaneFF Avatar
  • Blind4Basics Avatar
  • solitude Avatar
  • brodiemark Avatar
Ad