Recursive storage
Binary Trees
The TreeNode Object
• Data fields: Comparable value
reference to a left TreeNode
reference to a right TreeNode
• Methods: constructors
accessor methods (get)
mutator methods (set)
public class TreeNode public Comparable getValue()
{ { return value;
private Comparable value; }
private TreeNode left; public TreeNode getLeft()
private TreeNode right; { return left;
}
public TreeNode(Comparable v,
{ TreeNode l, TreeNode public TreeNode getRight()
r) { return right;
value = v; }
left = l;
public void setValue(Comparable v)
right = r; { value = v;
} }
public TreeNode(Comparable v) public void setLeft(TreeNode l)
{ { left = l;
value = v; }
left = null;
right = null; public void setRight(TreeNode r)
{ right = r;
}
}
• A Binary Tree is a dynamic-sized container composed
of TreeNodes.
• Each data value can point-to another value on its left
and right (left and right subtrees).
• The first element is called the root
– Every element can be considered a root of its own subtree.
root
B T
A D P Y
Using TreeNodes to make a Tree
TreeNode root = new TreeNode(“M”);
root
M
Using TreeNodes to make a Tree
TreeNode root = new TreeNode(“M”);
root
[Link](new TreeNode(“B”));
B
Using TreeNodes to make a Tree
TreeNode root = new TreeNode(“M”);
root
[Link](new TreeNode(“B”));
[Link](new TreeNode(“T”));
M
B T
Using TreeNodes to make a Tree
TreeNode root = new TreeNode(“M”);
root
[Link](new TreeNode(“B”));
[Link](new TreeNode(“T”));
M
TreeNode curr = [Link](); curr
[Link](new TreeNode(“A”));
B T
A
Using TreeNodes to make a Tree
TreeNode root = new TreeNode(“M”);
root
[Link](new TreeNode(“B”));
[Link](new TreeNode(“T”));
M
TreeNode curr = [Link](); curr
[Link](new TreeNode(“A”));
B T
[Link](new TreeNode(“D”));
A D
• The root stores an M
• The left-subtree stores [A, B, D]
• The right-subtree stores [P, T, Y]
• A leaf is a node with no children [A, D, P, Y]
– Its left and right pointers point to null
root
B T
A D P Y
• A descendant of a node is any value that is contained
in its subtree. The descendants of B are [A, D]
The descendants of M are [A, B, D, P, T,
Y]
• An ancestor of a node is any value that can be traced
up to the root. The ancestors of P are [T, M]
The root has no ancestors.
root
B T
A D P Y
• The depth of a node can be found by counting the
number of branches between the node going up
towards the root. The depth of M is 0
The depth of B is 1
The depth of Y is 2
• The depth or height of a tree is the maximum depth.
root
B T
A D P Y
• full binary tree: every node has two children or is a leaf.
• complete binary tree: nodes are added left-to-right,
completing a level before adding another.
complete full full not full
not full not complete complete not complete
Building Heaps
full & full &
complete complete complete complete
full & full & NOT FULL
complete complete complete NOT COMPLETE