Logo

Programming-Idioms

  • Python
  • Obj-c

Idiom #9 Create a Binary Tree data structure

The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.

@interface Node:NSObject
@property id value; // id means any object value
@property Node *left,*right;
@end

// usage like
Node *n=[Node new];
n.value=@1;
n.left=otherNode;
n.right=anotherNode;

// somewhere needed also
@implementation Node @end

The plain C solution is available too; the object-oriented solution probably better for most cases
class Node:
	def __init__(self, data):
		self.data = data
		self.left = None
		self.right = None
class Node:
  def __init__(self, data, left_child, right_child):
    self.data = data
    self._left_child = left_child
    self._right_child = right_child
type Tree_Node;
type Tree_Node_Access is access Tree_Node;
type Tree_Node is record
   Value: Integer;
   Left, Right: Tree_Node_Access;
end record;

New implementation...
< >
programming-idioms.org