trees trees
play

Trees Trees Nonrecursive definition: An edge connects parent and - PowerPoint PPT Presentation

CS206 CS206 Trees Trees Nonrecursive definition: An edge connects parent and child. A (rooted) tree consists of a set of nodes, and a set of directed A node without children is a leaf. edges between nodes. Nodes with the same parent are


  1. CS206 CS206 Trees Trees Nonrecursive definition: An edge connects parent and child. A (rooted) tree consists of a set of nodes, and a set of directed A node without children is a leaf. edges between nodes. Nodes with the same parent are siblings. • One node is the root; Depth of v is the length of the path from the root to v . • For every node c that is not the root, there is exactly one Height of v is the length of the longest path from v to a leaf. edge ( p, c ) pointing to c ; How many edges does a tree with n nodes have? • For every node c there is a unique path from the root to c . A tree with n nodes has n − 1 edges. Node Depth Height A 0 3 B 1 1 A A C 1 0 D 1 1 B C D E B C D E E 1 2 F 2 0 G 2 0 F G H I J F G H I J H 2 0 I 2 0 J 2 1 K K K 3 0 CS206 CS206 Recursive definition of trees Tree examples • A company organigram Recursive definition: A tree consists of a root, and zero or more subtrees T 1 , T 2 , . . . , T k . There is an edge from the root • A filesystem to the root of each subtree. Courses CS206 CS700 What is the base case of Slides Notes Code Articles the recursion? • A structured document (e.g. XML, HTML) • A recursion tree (function call tree) T 1 T 2 T 3 • An expression tree • A decision tree

  2. CS206 CS206 Phylogenetic tree of life Decision Trees We want to write a program to decode a transmission in Morse code. Bacteria Archaea Eukaryota To translate a letter, we make a GreenFilamentousbacteria Entamoebae Slimemolds Animals decision tree. Spirochetes Fungi Grampositives Methanosarcina Methanobacterium Halophiles Proteobacteria Plants E T Methanococcus Cyanobacteria Ciliates T. celer I A N M Planctomyces Thermoproteus Flagellates Pyrodicticum BacteroidesCytophaga Trichomonads S U R W D K G O Microsporidia Thermotoga H F L P B C Z Diplomonads Aquifex Q V J X Y CS206 CS206 Expression trees Displaying expressions def __str__(self): class Expression(): t = self.type() def __init__(self, data, left=None, right=None): self.data = data if t == "number": self.left = left return str(self.data) self.right = right if t == "variable": return self.data e = Expression("*", Expression("a"), if t == "unary": # unary minus Expression("+", return "-" + str(self.left) Expression(2), # it’s a binary operation Expression("-", return ("(" + str(self.left) + " " + self.data Expression("b"), expression.py + " " + str(self.right) + ")") Expression(7)))) Like list nodes, tree nodes are recursively defined types. This tree has two types of leaves (for numbers and for variables) and two types of inner nodes (for unary minus and for binary operations).

  3. CS206 CS206 Building expression trees Evaluating an expression tree: We can reuse our expression parser to build an expression tree. def evaluate(expr, vars): t = expr.type() Each method parse_item , parse_factor , parse_term , and if t == "number": parse_expression now returns an Expression . return expr.data if t == "variable": def parse_term(tok): if expr.data in vars: expr = parse_factor(tok) return vars[expr.data] t = tok[0] else: while t.isSymbol("*") or t.isSymbol("/"): raise EvalError("Undefined variable ’%s’" % expr.data) tok.pop(0) if t == "unary": arg = evaluate(expr.left, vars) rhs = parse_factor(tok) return -arg expr = Expression(t.value, expr, rhs) op = expr.data t = tok[0] lhs = evaluate(expr.left, vars) return expr rhs = evaluate(expr.right, vars) if op == "+": return lhs + rhs evaluate.py # and so on... CS206 CS206 Prefix notation Postfix notation The Lisp programming languages (Scheme, Racket) express Some programming languages (Forth, Postscript) are based on everything in prefix-notation: a stack, and need expressions in postfix notation: (* a (+ 2 (- b 7))) a 2 b 7 - + * def postfix(expr): def prefix(expr): t = expr.type() t = expr.type() if t == "number": if t == "number": return "%g" % expr.data return "%g" % expr.data if t == "variable": if t == "variable": return expr.data return expr.data if t == "unary": if t == "unary": return postfix(expr.left) + " chs" return "(- " + prefix(expr.left) + ")" return (postfix(expr.left) + " " + return ("(" + expr.data + postfix(expr.right) + " " + expr.data) " " + prefix(expr.left) + " " + prefix(expr.right) + ")") Compilers can create this code for a stack-based processor. prepostfix.py

  4. CS206 Tree traversals A tree traversal is the process of visiting all nodes of a tree, usually in a recursive manner. All operations on our expression trees (evaluating, conversion to string, prefix and postfix notation of expressions) are actually tree traversals. We distinguish three main types of tree traversals, depending on when the information in a node is processed: • Preorder traversal means that a node is processed before its children; • Postorder traversal means that a node is processed after its children; • Inorder traversal means that a node is processed between its left child and its right child (and is usually only used for binary trees).

Recommend


More recommend