32
1 Introduction to Binary Trees

1 Introduction to Binary Trees. 2 Background All data structures examined so far are linear data structures. Each element in a linear data structure has

  • View
    218

  • Download
    1

Embed Size (px)

Citation preview

1

Introduction to Binary Trees

2

Background

All data structures examined so far are linear data structures.

Each element in a linear data structure has a clear predecessor and a clear successor.

Predecessors and successors may be defined by arrival time or by relative size.

Trees are used to represent hierarchies of data.

Any element in a tree may have more than one successor - called it's children.

3

Terminology

Node or vertex - the labeled squaresEdge -the connecting linesIn the General tree to the right:

B is the child of A - A is parent of BB and C are siblingsA is the root of the treeB and its children (D, E, F) are a subtree of A

The parent-child relationship is generalized as ancestor -descendant.

B is a descendant of A - A is ancestor to B

A

CB

D E F

4

General Tree Definition

A General Tree T is a set of one or more nodes such that T is partitioned into disjoint subsets:

A single node R - the root

Sets that are general trees -the subtrees of R.

5

Binary Tree Definition

A Binary Tree is a set of nodes T such that either:

T is empty, or

T is partitioned into three disjoint subsets:

A single node R -the root

Two possibly empty sets that are binary trees, called the left and right subtrees of R.

6

Binary Tree Definition

T is a binary tree if either:

T has no nodes, or

T is of the form:R

TL TR

where R is a node and TL and TR are both binary trees.if R is the root of T then :

TL is the left subtree of R - if it is not null then its root is the left child of RTR is the right subtree of R - if it is not null then its root is the right child of R

7

Full Binary Trees

In a full binary tree:

All nodes have two children except leaf nodes.

All leaf nodes are located in the lowest level of the tree.

A

B

G

C

D E F

8

Complete Binary Trees

In a complete binary tree:

All nodes have two children except those in the bottom two levels.

The bottom level is filled from left to right.

A

B C

GE FD

H I G

9

Binary Search Trees

A binary search tree represents a hierarchy of elements that are arranged by size:

For any node n:

n's value is greater than any value in its left subtree

n's value is less than any value in its right subtree

F

D I

KE HB

A C G J

10

Binary Expression Trees

A binary expression tree represents an arithmetic expression:

For any node n:

if n is a leaf node:it must contain an operand.

if n is not a leaf node:it must contain an operator.it must have two subtrees.

*

+ -

db ca

This tree represents the expression:

(a + b) * (c -d) or

a b + c d -*

11

Binary Tree Traversals

A traversal of a binary tree "visits" each node and for each node:

Prints (or operates on) the data contained in that node.Visits the left subtree of the node.Visits the right subtree of the node.Recursive termination occurs when a visited node (or tree) is null.

There are three possible traversals of binary trees that differ only in the order that they perform the 3 basic operations.

12

Inorder Traversal

inorder (binTree tree) { //performs an inorder traversal of tree if(tree != null){ inorder(left subtree of tree) print tree's data inorder(right subtree of tree) }}

13

Inorder Traversal

inorder(binTree tree){ // inorder traversal of tree if(tree != null){ inorder(left subtree of tree) print tree's data inorder(right subtree of tree) }}

*

+ -

db ca

For this tree produces:a + b * c - d

14

Postorder Traversal

postorder(binTree tree){ //performs an postorder traversal of tree if(tree != null){ postorder(left subtree of tree) postorder(right subtree of tree) print tree's data }}

15

Postorder Traversal

postorder(binTree tree){ //postorder traversal of tree if(tree != null){ postorder(left subtree of tree) postorder(right subtree of tree) print tree's data }}

*

+ -

db ca

For this tree produces:a b + c d - *

16

Preorder Traversal

preorder(binTree tree){ //performs an preorder traversal of tree if(tree != null){ print tree's data preorder(left subtree of tree) preorder(right subtree of tree) }}

17

Preorder Traversal

preorder(binTree tree){ // preorder traversal of tree if(tree != null){ print tree's data preorder(left subtree of tree) preorder(right subtree of tree) }}

*

+ -

db ca

For this tree produces:* + a b - c d

18

class ExpressionTree -Inner class Tree

public class ExpressionTree { /** This inner class provides the structure for a tree node.*/ private class Tree { private char token; private Tree right; private Tree left; public Tree() { right = null; left = null; } public Tree(char tok, Tree lft, Tree rght) { token = tok; left = lft; right = rght; } } private Tree theTree;

// constants for precedence order private static final int LPAREN = 0; private static final int ADDITIVE = 1; private static final int MULTIPLICATIVE = 2; /** accessor for the Tree reference theTree */ public Tree getTree() { return theTree; } /** mutator for the Tree reference theTree */ public void setTree(Tree treeRef) { theTree = treeRef; }

19

class ExpressionTree -Inner class TreeStack

/** This inner class provides a stack of trees (tree nodes) for use in building * a binary expression tree from a String containing a postfix or infix expression.*/private class TreeStack{ /** This inner class provides the structure for a single item on the Tree Stack */ private class TreeStackNode { private Tree aNode; private TreeStackNode next; private TreeStackNode(Tree theNode, TreeStackNode nxt) { aNode = theNode; next = nxt; } private TreeStackNode(Tree theNode) { aNode = theNode; next = null; } } // end class TreeStackNode

private TreeStackNode theStack;

20

class ExpressionTree -Inner class TreeStack

private TreeStack( ) { theStack = null;}private void push(Tree aNode) { if(theStack == null) theStack = new TreeStackNode(aNode); else theStack = new TreeStackNode(aNode, theStack);}

private Tree pop( ) { if(theStack != null) { Tree temp = theStack.aNode; theStack = theStack.next; return temp; } else return null;}

private Tree top(){ if(theStack != null){ Tree temp = theStack.aNode; return temp; } else return null; } } // end class TreeStack

21

Building an Expression Tree from aPostfix Expression

Similar to postfix evaluation algorithm

Requires a stack of operands

Here an operand is a tree in which:

nodes containing variable names are leaves.

nodes containing operators have at least two children which can be other operators or leave nodes.

Also requires a String containing the postfix expression.

22

Building an Expression Tree from aPostfix Expression

For each token in postfix expressionIf token is an operand

Form a tree node and push on the tree stackElse if token is an operator (+, -, *, /)

Form a tree node with the operatorPop the stack and attach the operand popped as the right child of the operator node.Pop the stack and attach the operand popped as the left child of the operator node.Push the operator node.

When input string is empty the final tree can be popped off the tree stack.

23

Postfix Expression Tree -Trace

A B C D * - + E /

B

B

Stack

A

A

StackA

B

C

StackA

D

Stack

C

B

A

C

D*

Stack

B

A

C D

*

24

Postfix Expression Tree -Trace

A B C D * - + E /

Stack

E

-

B

C D

-

*

Stack

+

A

B

C D

-

*

+

Stack

E

A

B

C D

-

*

+

Stack

/

/

E

A

B

C D

-

*

+

25

Building an Expression Tree from anInfix Expression

Similar to infix to postfix conversion

Must account for operator precedence and associativity.

Precedence: / , * = 3 + , -= 2 ( = 0

Requires two stacks (of trees):

one for operators.

one for operands.

Also requires a String containing the postfix expression.

26

Building an Expression Tree from anInfix Expression

For each token in postfix expressionIf token is an operand (letter)

Form a tree node and push on the operand stack.

If token is a left paren ‘(‘Form a tree node and push the left paren onto the operator stack

27

Building an Expression Tree from anInfix Expression

Else if token is an arithmetic operator (+, -, *, /)Form a tree node with the operatorwhile(operator stack is not empty AND

precedence(token operator) <= precedence(top of operator stack)

pop tree node off operator stack pop tree off operand stack - attach to right

of operator node pop tree off operand stack - attach to left

of operator node push operator node onto operand stackpush node with the new token onto the operator stack

28

Building an Expression Tree from anInfix Expression

Else if token is )while(token on top of operator stack is not '(' )

pop tree node off operator stack pop tree off operand stack - attach to

right of operator node pop tree off operand stack - attach to left

of operator node push operator node onto operand stackpop the operator stack - removes (

29

Building an Expression Tree from anInfix Expression

After all tokens in postfix expression have been used

while(operator stack is not empty) pop tree node off operator stack pop tree off operand stack - attach to

right of operator node pop tree off operand stack - attach to left

of operator node push operator node onto operand stackWhen the operator stack is empty the final tree can be popped off the operand stack.

30

Infix Expression Tree -Trace

A + B * C - D

A

A

OperandStack

+

A +

OperatorStack

OperandStack

OperatorStack

B

B+

OperandStack

OperatorStack

A

31

Infix Expression Tree -Trace

A + B * C - D*

B

+

OperandStack

OperatorStack

A

*

C

B

+

OperandStack

OperatorStack

A

*

C

-(1)

B

OperandStack

OperatorStack

A

C

*

+

32

Infix Expression Tree -Trace

A + B * C - D

- (2)

B -

OperandStack

OperatorStack

A

C

*

+

Finish

OperandStack

OperatorStack

D

-

OperandStack

OperatorStack

D

B

A

C

*

+

B

A

C

*

+

-

D