Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures( 数据结构 ) Course 7:Tree. 2 西南财经大学天府学院 Vocabulary Tree 树 Subtree 子树 Branch 分枝 Indegree 入度 Outdegree 出度 Degree 度 Leaf 叶子 Internal node 内部结点.

Similar presentations


Presentation on theme: "Data Structures( 数据结构 ) Course 7:Tree. 2 西南财经大学天府学院 Vocabulary Tree 树 Subtree 子树 Branch 分枝 Indegree 入度 Outdegree 出度 Degree 度 Leaf 叶子 Internal node 内部结点."— Presentation transcript:

1 Data Structures( 数据结构 ) Course 7:Tree

2 2 西南财经大学天府学院 Vocabulary Tree 树 Subtree 子树 Branch 分枝 Indegree 入度 Outdegree 出度 Degree 度 Leaf 叶子 Internal node 内部结点 Level 层 Height(depth) 高度(深度) Chart format 图格式 Indented list 缩进表(锯齿状表) Parenthetical list 多层括号表 ( 广义表 ) Binary tree 二叉树 Balance 平衡 Balance factor 平衡因子 Complete binary trees 完全二叉树 Traversal 遍历 depth first 深度优先 breadth first 广度优先 Preorder traversal 先 ( 根次 ) 序遍历 inorder traversal 中序遍历 Postorder traversal 后序遍历 Infix (post pre ) 中 ( 后 前 ) 缀表达式 Operator 运算符 Operand 运算分量 Hufman code 哈夫曼编码 Weight 权值 Binary search tree 二分查找树 AVL 平衡二叉树

3 3 西南财经大学天府学院 Chapter 7 introduction to trees 7-1 Basic tree concepts List Tree Tree: consists of a finite set of elements(nodes), and a finite set of directed lines (branches) that connect the nodes A G D F C E B Recall that a list is a collection of components in which 1.each component (except one, the first) has exactly 1 predecessor. 2.each component (except one, the last) has exactly 1 successor. a tree is very similar: it has property (1) but (2) is slightly relaxed Figure 7-1 A tree

4 4 西南财经大学天府学院 Root: the first node Indegree = zero A G D F C E B Degree: the number of branches (the sum of indegree and outdegree) Outdegree:branch is directed away from the node Indegree:branch is directed toward the node All of the nodes (exception of the root)have only one indegree,but have zero,one and more outdegree Note : empty tree, no node Basic tree concepts

5 5 西南财经大学天府学院 terminology A G D F C E B Leaf: node with an outdegree of zero Internal node: is not a root or a leaf Parent: has successor nodes (outdegree > 0) Child: a node with a predecessor (indegree=1) Siblings: nodes with the same parent Ancestor: any node in the path from the root to the node Descendent: any node in the path below the parent node Path: a sequence of nodes in which each node is adjacent to the next one, every node can be reached from the root such as ADG,ABE,… Branch AD Branch DG

6 6 西南财经大学天府学院 Terminology A G D F C E B Level of a node is its distance from the root Root: level 0 The children of root level 1 Siblings at the same level Level 0 Level 1 Level 2 Height(depth) of the tree is the level of the leaf in the longest path from the root+1 ( = 3 ) The height of an empty tree is 0 ( 书上为 -1) A G D F C E B

7 7 西南财经大学天府学院 Subtree B Subtree C Subtree D Subtree: divided from a tree,any connected structure below the root, Subtrees can be subdivided into subtrees A G D F C E B Terminology Recursive definition of a tree A tree is a set of nodes that either (1)Empty (2)Has a designated node—root,from which hierarchically descent zero or more subtrees,which are also trees

8 8 西南财经大学天府学院 Tree representation Tree is implemented in computer using pointers,there are three representations outside the computer computer caseCPU3.5 ” diskCD-ROM ROMALUcontroller 1Computer 1-1 case 1-2 CPU controller ALU … ROM ” Disk … 1-9 CD-ROM Chart format: general tree Indented list: bill-of-materials (goezinta, goes into) Parenthetical listing: 广义表 To convert a tree to PN uses algebraic expressions, Open parenthesis indicates the start of a new level, each closing parenthesis completes the current level and moves up one level in the tree, consider the tree in Figure 7-1,its parenthetical notation is A ( B ( E ) C D ( F G ) ) Algorithm converttoparen (val root, ref output ) Convert a general tree to parenthetical notation. Pre root is a pointer to a tree node Post output contains parenthetical notation 1 place root in output 2 if ( root is a parent ) 1 place an open parenthesis in the output 2 converttoparen ( root’s first child ) 3 loop ( more siblings ) 1 converttoparen ( root’s next child ) 4 end loop 5 place close parenthesis in the output 3 end if 4 return End converttoparen

9 9 西南财经大学天府学院 7-2 Binary trees A F E DC B Left subtree Right subtree No node can have more than two subtrees, or a node can have zero,one, or two subtrees are designated as left subtree and right subtree

10 10 西南财经大学天府学院 Several binary trees (a) (g)(h)(f)(e) (d)(c) (b) A A B A B A BC A CB ED A B C A B C Figure 7-6 A collection of binary trees Null tree, with no nodes symmetry is not required

11 11 西南财经大学天府学院 properties 二叉树第 i 层上至多有 2 i 结点 深度为 k 的二叉树最多有 2 k -1 个结点 对任何一棵二叉树有 n 0 =n 2 +1 对一棵有 n 个结点的完全二叉树,按层编号对任一结点有 i=1 为根结点 i>1 双亲结点 2i>n, 则 i 无左孩子,否则左孩子为 2i 2i + 1>n, 则 i 无右孩子,否则右孩子为 2i+1

12 12 西南财经大学天府学院 properties Height of binary trees Balance Balance factor Complete binary trees Nearly complete tree The distance of a node from the root determines the efficiency it can be located The children of any node: only one branch path Nodes at level 2 : two braches from the root So the shorter the tree, the easier to locate any desired node Balance factor(B) is the difference in height between its left and right subtrees ( H L, H R ) B = H L – H R A tree is balanced if its balance factor is 0 and its subtrees are also balanced (seldom) More generally, is –1, 0, +1 Given the nodes of the binary tree, N The height of the tree H max = N all in one direction(branch) H min = +1 Given a height of the binary tree,H The number of nodes in the tree N min = H N max = 2 H - 1 A complete tree has the maximum number of entries for its height.the maximum number is reached when the last level is full. such as A BC A CB ED A EF If it has the minimum height for its nodes and all nodes in the last level are found on the left. such as A BC A CB ED A F DE CB D

13 13 西南财经大学天府学院 Binary tree structure leftsubtree data rightsubtree The node of binary tree Node leftsubtree data rightsubtree End node Traditionally, the subtree pointers are simply called left and right

14 14 西南财经大学天府学院 Binary tree traversals Traversal: each node of the tree be processed once and only once in a predetermined sequence Approaches: depth first and breadth first Depth first traversal: the processing proceeds along a path from the root through one child to the most distant descendent of that first child before processing a second child. Process all of the descendents of a child before going on to the next child. breadth first traversal: the processing proceeds horizontally from the root to all of its children, then to its children’s children. And so forth until all nodes have been processed Each level is completely processed before the next level is started

15 15 西南财经大学天府学院 Depth-first traversals Given that a binary tree consists of root, a left subtree, and a right subtree We can define 6 different depth –first traversal sequences. Computer scientist have assigned three of these sequences standard names in the literature Left subtreeRight subtree (a) Preorder traversal(b) inorder traversal (c) postorder traversal Figure 7-8 binary tree traversals Traditional designation: N- root, L-leftsubtree, R-right subtree

16 16 西南财经大学天府学院 Preorder traversal (NLR) Note:The root node is processed first, before the left subtree, right subtree Recursive algorithm: Algorithm preOrder (val root ) Traverse a binary tree in node-left-right sequence Pre root is the entry node of a tree or subtree Post each node has been processed in order 1 if (root is not null) 1 process (root) 2 preOrder (root->leftsubtree) 3 preOrder (root->rightsubtree) 2 end if 3 return End preOrder Algorithm 7-2 preorder traversal of a binary tree example A F E DC B Figure 7-9 a binary tree for traversals A F E DC B Walking order A B C D E F

17 17 西南财经大学天府学院 Inorder traversal (LNR) Note: in the inorder traversal, the node is processed between Its subtrees. left subtree—root—right subtree Recursive algorithm: Algorithm inOrder (val root Traverse a binary tree in left-node-right sequence Pre root is the entry node of a tree or subtree Post each node has been processed in order 1 if (root is not null) 1 inOrder (root->leftsubtree) 2 process (root) 3 inOrder (root->rightsubtree) 2 end if 3 return End preOrder Algorithm 7-3 inorder traversal of a binary tree example A F E DC B Walking order C B D A E F

18 18 西南财经大学天府学院 Postorder traversal (LRN) Note:in the postorder traversal, the root is processed after the subtrees. left subtree—right subtree—root Recursive algorithm: Algorithm postOrder (val root Traverse a binary tree in left-right-node sequence Pre root is the entry node of a tree or subtree Post each node has been processed in order 1 if (root is not null) 1 postOrder (root->leftsubtree) 2 postOrder (root->rightsubtree) 3 process (root) 2 end if 3 return End postOrder Algorithm 7-4 postorder traversal of a binary tree example A F E DC B Walking order C D B F E A Note: we took the same path in all three walks; Only the time of the processing changed.

19 19 西南财经大学天府学院 Breadth-first traversals Note : We process all of the children of a node before proceeding with the next level. Algorithm Uses queue Algorithm breadthfirst (val root Process tree using breadth-first traversal. Pre root is a pointer to a tree node Post tree has been processed 1 pointer = root 2 loop ( pointer not null ) 1 process ( pointer ) 2 if (pointer->left not null ) 1 enqueue ( pointer->left ) 3 end if 4 if (pointer->right not null ) 1 enqueue ( pointer->right ) 5 end if 6 if ( not emptyQueue ) 1 dequeue ( pointer ) 7 else 1 pointer = null 8 end if 3 end loop 4 return End breadthfirst Algorithm 7-5 breadth-first tree traversal example A F E DC B A B E CD F

20 20 西南财经大学天府学院 7-4 expression trees An expression is a sequence of tokens that follow prescribed rules. Token may be either an operand or an operator. We consider only binary arithmetic operators in the form Operand—operator—operand The properties of an expression tree 1.Each leaf is an operand 2.The root and internal nodes are operators 3.Subtrees are subexpressions, with the root being an operator. + + * a bc d a*(b+c)+d An infix expression and its expression tree The traversal of expression tree Three standard traversals represent the three different expression formats: infix, postfix, and prefix. The inorder traversal produces the infix expression The postorder traversal produces the postfix expression The preorder traversal produces the prefix expression

21 21 西南财经大学天府学院 Infix traversal Traverses the tree and print infix expression Add opening parenthesis’ ( ‘at the beginning of each expression Add closing parenthesis ’ ) ‘at the end of each expression Note: root of the tree and each of its subtree represent a subexpression, so print (: when we start a tree or subtree ): when we have processed all of its children + + * a bc d ((a*(b+c))+d) ( ( ( ) ) ) Algorithm infix (val tree Print the infix expression for an expression tree. Pre tree is a pointer to an expression tree Post the infix expression has been printed 1 if ( tree not null ) 1 if ( tree->token is an operand ) 1 print ( tree->token ) 2 else 1 print ( open parenthesis ) 2 infix ( tree->left ) 3 print ( tree->token ) 4 infix ( tree->right ) 5 print ( close parenthesis ) 3 end if 2 end if 3 return End infix Algorithm 7-6 infix expression tree traversal Algorithm:

22 22 西南财经大学天府学院 Postfix traversal As same as posorder traversal of any binary tree Note : it does not require parentheses Algorithm: Algorithm postfix (val tree Print the postfix expression for an expression tree. Pre tree is a pointer to an expression tree Post the postfix expression has been printed 1 if ( tree not null ) 1 postfix ( tree->left ) 2 postfix ( tree->right ) 3 print ( tree->token ) 2 end if 3 return End postfix Algorithm 7-7 postfix expression tree traversal Result : a b c + * d + Operation : scan from left one to right, when meet +,do b+c=x, we get ax*d+, continue,meet *, do a*x=y, get yd+, continue, y+d, this is the result. Result:

23 23 西南财经大学天府学院 Prefix traversal As same as preorder traversal of any binary tree Note : it does not require parentheses Algorithm: Algorithm prefix (val tree Print the prefix expression for an expression tree. Pre tree is a pointer to an expression tree Post the prefix expression has been printed 1 if ( tree not null ) 1 print ( tree->token ) 2 prefix ( tree->left ) 3 prefix ( tree->right ) 2 end if 3 return End prefix Algorithm 7-8 prefix expression tree traversal Result : + * a + b c d Operation : scan from left one to right, when meet b c,do b+c=x, we get + * a x d, continue, meet a x, do a*x=y, get + y d, continue, y+d, this is the result. Result:

24 24 西南财经大学天府学院 General tree Each node can have an unlimited outdegree Each node may have as many children as necessary. Example: the bill of materials (p268)

25 25 西南财经大学天府学院 Changing general tree to binary tree It is easier to represent binary tree than general tree Use two relationships: parent to child, sibling to sibling A BE C F DHGI (a)general tree A BE C F DHGI (b)identify leftmost children A BE C F DHGI ( c ) connect siblings A BE C F DHGI (d) Delete unneeded branches A B E C F D H G I (e)the resulting binary tree

26 26 西南财经大学天府学院 7-6 Huffman code ASCII & EBCDIC are fixed_length codes. Ignore occurs frequent Huffman code assign shorter codes to characters that occur more frequently. A popular data compression algorithm Before we can assign bit patterns to each character, we assign each character a weight based on its frequency of use. E=15T=12A=10O=08R=07N=06S=05 U=05I=04D=04M=03C=03G=02K=02 Table 7-2 character weights for a sample of Huffman code

27 27 西南财经大学天府学院 build a tree We can build a tree based on weight values The basic steps: 1. organize the entire character set into a row, ordered according to frequency from highest to lowest, each character is now a node at the leaf level of a tree. 2. Find the two nodes with the smallest combined frequency weights and join them to form a third node, resulting in a simple two-level tree.the weight of the new node is the combined weights of the original two nodes. This node is eligible to be combined with other nodes. 3. Repeat step 2 until all of the nodes, on every level, are combined into a single tree. E 15 T 12 A 10 O 08 R 07 N 06 S 05 U I 04 D M 03 C G 02 K E 15 T 12 A 10 O 08 R 07 N 06 S 05 U I 04 D M 03 C GK 04 AOSUIDER N MCGKT

28 28 西南财经大学天府学院 Figure shows the process Note : in the sixth row, the lowest-value node is 08(O), the second lowest value is 10(A). But there are three 10s: (A), (S-U) and (M-C- G-K) We choose whichever of the 10s is adjacent to the 8. To keeps the branch lines from crossing and allows us to preserve the legibility of the tree. If none of the higher values are adjacent to the lower value, we can rearrange the nodes for clarity To assign codes: 0 to the left branch (or 1) 1 to the right branch (or 0) A character’s code: starting at the root and following the branches that lead to that character. The code is the bit value of each branch on the path taken in sequence. The leading bits of each code are unique, that is, no code is the prefix of any other code

29 29 西南财经大学天府学院 AOSUIDER N MCGKT A=000 U=0101 E=100 M=11000 K=11011 O=001 I=0110 R=1010 C=11001 T=111 S=0100 D=0111 N=1011 G=11010 Figure 7-24 Huffman code assignment The result

30 30 西南财经大学天府学院 7-7 summary Tree consists of nodes(elements) and branch(directed lines) Degree – the number of branches associated with a node Indegree—directed toward the node Outdegree — directed away from the node Root—the first node with indegree of zero All node,except root have an indegree of one Leaf—with an outdegree of zero Internal node—neither the root nor the leaf Parent, child, siblings Path—a sequences of nodes in which each node is adjacent to the next one An ancestor—any node in the path from the root of a given node Descendent—any node in all of the paths from a given node to a leaf Level—the distance from the root Height—the level of the leaf in the longest path from the root +1 Subtree—any connected structure below the root Binary tree—no node have more than two children H min = H max = N H min = H N max = 2 n + 1

31 31 西南财经大学天府学院 7-7 summary Balance factor : B = H L - H R Balanced tree B = 0 Binary balanced tree B <= 1 Complete tree—the last level is full nearly complete tree—has the minimum height for its nodes and all nodes in the last level are found on the left A binary tree traversal – visits eachnode of the tree once and only once in a predetermined sequence Depth first—preorder(NLR), inorder(LNR), postorder(LRN),… Breadth-first—process all nodes in a level before processing to the next level A general tree—each node can have an unlimited outdegree Changing a general tree to a binary tree—identify the leftmost children ; connected the siblings from left to right ; delete the unused branches Huffman code—uses a variable-length code to represent characters, shorter code assigns to characters that occur more frequently To create Huffman code—determine the number of occurrences for each character; put the entire character set into a row(leaves of a tree); find the two nodes with the smallest combined frequency weights and link them to a new node to form a tree whose parent’s weight is the sum of the two nodes; repeat until nodes on all levels are combined into a single tree

32 32 西南财经大学天府学院 Exercises A binary tree has ten nodes. The inorder and preorder traversal of the tree are shown below. Draw the tree Preorder: JCBADEFIGH Inorder: ABCEDFJGIH A nearly complete binary tree has nine nodes. The breadth traversal of the tree is given below. draw the tree JCBADEFIG Draw the expression tree and find the infix and prefix expressions for the following postfix expression: *-AB+*CD/EF According to weight value W=(2,5,7,9,13) build a Huffman tree, write Huffman code of each leaf node.


Download ppt "Data Structures( 数据结构 ) Course 7:Tree. 2 西南财经大学天府学院 Vocabulary Tree 树 Subtree 子树 Branch 分枝 Indegree 入度 Outdegree 出度 Degree 度 Leaf 叶子 Internal node 内部结点."

Similar presentations


Ads by Google