


















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



















2
General tree
Binary tree
Not a tree
8 List-like tree
4
Points
to
left
subtree
Points
to
right subtree
8
-^
Expression
grammar:
integer
-^
In
textual
representation
Parentheses
show
hierarchical
structure
-^
In
tree
representation
-^
Hierarchy
is^
explicit
in^
the
structure
of
the
tree
Text
AST Representation
10
public static boolean treeSearch(Object x,
TreeCell node) {
if (node == null) return false;if (node.datum.equals(x)) return true;return treeSearch(x, node.left) ||
treeSearch(x, node.right);
ļ^ Analog of linear search in lists:given tree and an object, find out ifobject is stored in tree ļ^ Easy to write recursively, harder towrite iteratively
11
All
left
descendents
of^ node
come
before
node
ļ¤^
All^ right
descendents
of^
node
come
after
node
public static boolean treeSearch (Object x, TreeCell node) {
if (node == null) return false;if (node.datum.equals(x)) return true;if (node.datum.compareTo(x) > 0)
return treeSearch(x, node.left); else return treeSearch(x, node.right); }
13
jan feb
mar
apr
may
jun jul
14
-^ Recursively
-^ Recursively
/* Show the contents of the BST in* alphabetical order./public void show () {*
show(root);System.out.println(); } private static void show(TreeNode node) {
if (node == null) return;show(node.lchild);System.out.print(node.datum + " ");show(node.rchild); }
16
//determine
if
a
node
is
a
leaf
public
static boolean
isLeaf(TreeCell
node)
{
return
(node
!=
null)
&&
(node.left
==
null)
&&
(node.right
==
null);
} //compute
height
of
tree
using
postorder
traversal
public
static int
height(TreeCell
node)
{
if
(node
==
null)
return
-1;
//empty
tree
if
(isLeaf(node))
return
0;
return
1
+
Math.max(height(node.left),
height(node.right));
} //compute
number
of
nodes
using
postorder
traversal
public
static int
nNodes(TreeCell
node)
{
if
(node
==
null)
return
0;
return
1
+
nNodes(node.left)
+
nNodes(node.right);
}
ļ¤Minimum
number
of
nodes
in tree
=^ h
ļ¤Maximum
number
of
nodes
in tree
0 +^
(^1 ) +^ ā¦
+^2
h^ =
h+1 2
-^1
All
levels
of
tree
down
to
a^ certain
depth
are
completely
filled
17
depth 0 1 2
Height 2,maximum number of nodesHeight 2,minimum number of nodes
19
jan feb
mar
apr
may
jun jul
20