Trees Neil Tang 01262010 CS 223 Advanced Data

  • Slides: 11
Download presentation
Trees Neil Tang 01/26/2010 CS 223 Advanced Data Structures and Algorithms 1

Trees Neil Tang 01/26/2010 CS 223 Advanced Data Structures and Algorithms 1

Class Overview Ø Basics Ø Binary Tree Traversal Ø General Tree CS 223 Advanced

Class Overview Ø Basics Ø Binary Tree Traversal Ø General Tree CS 223 Advanced Data Structures and Algorithms 2

Basics Ø Tree: A tree consists of a distinguished node r (root) and zero

Basics Ø Tree: A tree consists of a distinguished node r (root) and zero or more nonempty subtrees T 1, T 2, …Tk, each of whose roots are connected by a direct edge from r. Ø Child, parent, leaf, sibling Ø Path and path length Ø Depth of a node, depth of a tree Ø Height of a node, height of a tree Ø Ancestor, descendant CS 223 Advanced Data Structures and Algorithms 3

An Example CS 223 Advanced Data Structures and Algorithms 4

An Example CS 223 Advanced Data Structures and Algorithms 4

Properties Ø No cycle. Ø There only exists a unique path between a pair

Properties Ø No cycle. Ø There only exists a unique path between a pair of nodes on a tree. Ø The height of a tree = the depth of that tree. CS 223 Advanced Data Structures and Algorithms 5

Binary Tree Ø Binary tree: A binary tree is a tree in which no

Binary Tree Ø Binary tree: A binary tree is a tree in which no node can have more than two children. Ø Implementation Ø The depth of a worst-case binary tree: N-1 CS 223 Advanced Data Structures and Algorithms 6

Binary Tree Traversal Inorder-Tree-Traversal(t) if t null then Inorder-Tree-Traversal(t. left) print(t. element) Inorder-Tree-Traversal(t. right)

Binary Tree Traversal Inorder-Tree-Traversal(t) if t null then Inorder-Tree-Traversal(t. left) print(t. element) Inorder-Tree-Traversal(t. right) Preorder-Tree-Traversal(t) if t null then print(t. element) Preorder-Tree-Traversal(t. left) Preorder-Tree-Traversal(t. right) How about Postorder-Tree-Traversal? CS 223 Advanced Data Structures and Algorithms 7

An Example Inorder: x*a*b+c Preorder: *x+*abc Postorder: xab*c+* CS 223 Advanced Data Structures and

An Example Inorder: x*a*b+c Preorder: *x+*abc Postorder: xab*c+* CS 223 Advanced Data Structures and Algorithms 8

General Tree Ø Implementation CS 223 Advanced Data Structures and Algorithms 9

General Tree Ø Implementation CS 223 Advanced Data Structures and Algorithms 9

General Tree Traversal Ø Preorder Ø What is the first node visted? Last? CS

General Tree Traversal Ø Preorder Ø What is the first node visted? Last? CS 223 Advanced Data Structures and Algorithms 10

General Tree Traversal Ø Postorder Ø What is the first node visited? Last? CS

General Tree Traversal Ø Postorder Ø What is the first node visited? Last? CS 223 Advanced Data Structures and Algorithms 11