【数据结构英文课件】BINARY TREES_第1页
【数据结构英文课件】BINARY TREES_第2页
【数据结构英文课件】BINARY TREES_第3页
【数据结构英文课件】BINARY TREES_第4页
【数据结构英文课件】BINARY TREES_第5页
已阅读5页,还剩77页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Chapter 10 BINARY TREES,1. General Binary Trees,2. Binary Search Trees,3. Building a Binary Search Tree,4. Height Balance: AVL Trees,5. Splay Trees,6. Pointers and Pitfalls,10.1 Binary Trees,DEFINITION A binary tree is either empty, or it consists of a node called the root together with two binary t

2、rees called the left subtree and the right subtree of the root.,1. Definitions,2. Traversal of Binary Trees,At a given node there are three tasks to do in some order: Visit the node itself (V); traverse its left subtree (L); traverse its right subtree (R). There are six ways to arrange these tasks:,

3、VLR LVR LRV VRL RVL RLV,By standard convention, these are reduced to three by considering only the ways in which the left subtree is traversed before the right.,preorder,preorder,inorder,inorder,postorder,postorder,These three names are chosen according to the step at which the given node is visited

4、.,With preorder traversal we first visit a node, then traverse its left subtree, and then traverse its right subtree. With inorder traversal we first traverse the left subtree, then visit the node, and then traverse its right subtree. With postorder traversal we first traverse the left subtree, then

5、 traverse the right subtree, and nally visit the node.,See pg.432-434,Expression tree,x = (-b+(b2-4ac)0.5) / (2a),3. Linked implementation of Binary Trees,Node structure of Binary Trees,example,Linked Binary Trees Specifications,template class Binary_tree public: / Add methods here. protected: / Add

6、 auxiliary function prototypes here. Binary_node *root; ;,Binary trees class,二叉树根结点指针,template struct Binary_node Entry data; Binary_node *left; Binary_node *right; Binary_node( ); Binary_node(const Entry ,Binary node class,数据域,指向左孩子的指针,指向右孩子的指针,template void Binary_tree:inorder(void (*visit)(Entry

7、,Inorder traversal:,method,函数参数 (访问数据),调用递归中序 遍历函数,递归中序遍历函数 多一个参数,树形结构是一类重要的非线性结构。树能够很好地描述结构的分支关系和层次特性,它非常类似于自然界中的树。树结构在客观世界中是大量存在的,例如家谱以及行政组织机构都可用树形象地表示。树在计算机领域中也有着广泛的应用,如在编译程序中,用树来表示源程序语法结构;在数据库系统中,可以用树来组织信息。本章重点讨论二叉树的存储表示及其各种运算,要求大家要学会编写实现二叉树的各种运算的算法。 二叉树是递归定义的,因此递归是它的固有特性,本小节的练习中就要求大家完成许多操作二叉树的算

8、法,且是递归算法。 下面我们给出一个以先序方式创建任意二叉树的算法,请 认真学习。,template void Binary_tree:CreatBinary_tree() CreatBinary_tree(root); template void Binary_tree: CreatBinary_tree(Binary_node* ,建立二叉链表 表示的二叉树,递归建立以r为 根结点指针的二叉链表 表示的二叉树,建立”空”二叉树,建立根结点,建立根结点 的左子树,建立根结点 的右子树,Entry data member,Entry data member,表示空的 数据,我们再给出一个应用例

9、。,在以二叉链表存储的二叉树中查找值为x的结点,请编写一非递归算法:打印值为x的结点的所有的祖先结点的值。设值为x的结点不多于1个。,template printAncestors(Binary_tree tree, T ,在二叉树tree中搜索 结点x,找到则打印 所有祖先结点及x 否则输出x不存在,要求非递归 因此自行定义 栈结点类型,指针域(保留从根到 搜索结点路径上 所以结点指针),标记域 (tag=0左子树 否则是右子树),置空栈,栈数组,栈结点类型名,取得二叉树tree 的根结点指针 做为t的初始值,指针不空而且 其所指结点的 数据域不是x,栈不空,搜索左子树 寻找值为x的结点,进

10、栈,二叉树tree 的根结点是x,if (t ,找到值为x的结点 输出所有祖先结点 (栈),跳出while循环,如果栈顶是右指针 弹出,如果栈不空 栈顶是左指针 转向右子树 重新回到while,没找到值为x的结点,在C+环境下演示创建二叉树及在建立的二叉树上完成各项操作的bt_main.cpp。,10.2 Binary Search Trees,Can we find an implementation for ordered lists in which we can search quickly (as with binary search on a contiguous list) an

11、d in which we can make insertions and deletions quickly (as with a linked list)?,A binary search tree is a binary trees that is either empty or in which the data entry of every node has a key and satisfies the conditions: 1. The key of the root (if it exists) is greater than the key in any node in t

12、he left subtree of the root. 2. The key of the root (if it exists) is less than the key in any node in the right subtree of the root. 3. The left and right subtrees of the root are again binary search trees.,binary search tree Definitions pg.445,binary searchtree not binary searchtree,DEFINITION A b

13、inary search tree is a binary tree that is either empty or in which the data entry of every node has a key and satises the conditions: 1. The key of the left child of a node (if it exists) is less than the key of its parent node. 2. The key of the right child of a node (if it exists) is greater than

14、 the key of its parent node. 3. The left and right subtrees of the root are again binary search trees.,error,error,We always require: No two entries in a binary search tree may have equal keys., We can regard binary search trees as a new ADT. We may regard binary search trees as a specialization of

15、binary trees. We may study binary search trees as a new implementation of the ADT ordered list. The binary search tree class will be derived from the binary tree class; hence all binary tree methods are inherited.,1. Ordered Lists and Implementations pg.446,The Binary Search Tree Class pg.446,templa

16、te class Search_tree:public Binary_tree public: Error_code insert(const Record ,The inherited methods include the constructors, the destructor,clear, empty, size, height, and the traversals preorder, inorder,and postorder.,A binary search tree also admits specialized methods called insert, remove, a

17、nd tree search.,The class Record has the behavior outlined in Chapter 7: Each Record is associated with a Key. The keys can be compared with the usual comparison operators. By casting records to their corresponding keys, the comparison operators apply to records as well as to keys.,2. Tree Search pg

18、.447,Error_code Search_tree: tree_search(Record Post: If there is an entry in the tree whose key matches that in target, the parameter target is replaced by the corresponding record from the tree and a code of success is returned. Otherwise a code of not_present is returned.,This method will often b

19、e called with a parameter target that contains only a key value. The method will fill target with the complete data belonging to any corresponding Record in the tree.,To search for the target, we first compare it with the entry at the root of the tree. If their keys match, then we are finished. Othe

20、rwise, we go to the left subtree or right subtree as appropriate and repeat the search in that subtree.,We program this process by calling an auxiliary recursive function.,The process terminates when it either finds the target or hits an empty subtree., The auxiliary search function returns a pointe

21、r to the node that contains the target back to the calling program. Since it is private in the class, this pointer manipulation will not compromise tree encapsulation.,Binary_node* Search_tree: search_for_node(Binary_node *sub_root, const Record tree_search usually performs almost as well as binary

22、search.,3.Insertion into a Binary Search Tree pg.451,Error_code Search tree: insert(const Record Post: If a Record with a key matching that of new data already belongs to the Search tree a code of duplicate_error is returned. Otherwise, the Record new data is inserted into the tree in such a way tha

23、t the properties of a binary search tree are preserved, and a code of success is returned.,Method for Insertion,template Error_code Search_tree:insert(const Record ,“空”BST 直接插入(根结点),寻找 插入位置,插入数据小于 当前(子树根)结点数据 继续在左子树中 搜寻插入位置,在右子树中 搜寻插入位置,直至到达一个空BST 子树,脱离循环;这时 插入结点应是parent 的孩子,sub_root=new Binary_node

24、(new_data); if(new_datadata) parent-left=sub_root; else parent-right = sub_root; return success; ,根据插入结点值 确定应是parent 的左孩子还是右孩子?,The method insert can usually insert a new node into a random binary search tree with n nodes in O(n) steps. It is possible, but extremely unlikely, that a random tree may

25、degenerate so that insertions require as many as n steps. If the keys are inserted in sorted order into an empty tree, however, this degenerate case will occur.,See pg.453 Theorem 10.1 and Corollary 10.2,When a binary search tree is traversed in inorder, the keys will come out in sorted order. This

26、is the basis for a sorting method, called treesort: Take the entries to be sorted, use the method insert to build them into a binary search tree, and then use inorder traversal to put them out in order.,Theorem 10.1 Treesort makes exactly the same comparisons of keys as does quicksort when the pivot

27、 for each sublist is chosen to be the first key in the sublist.,4. Treesort pg.453,Corollary 10.2 In the average case, on a randomly ordered list of length n, treesort performs comparisons of keys.,First advantage of treesort over quicksort: The nodes need not all be available at the start of the pr

28、ocess, but are built into the tree one by one as they become available. Second advantage: The search tree remains available for later insertions and removals. Drawback: If the keys are already sorted, then treesort will be a disaster- the search tree it builds will reduce to a chain. Treesort should

29、 never be used if the keys are already sorted,or are nearly so.,5.Removal from a Binary Search Tree pg.455,从二叉查找(搜索/排序)树中删除一个结点,不能把以该结点为根的子树都删除,只能删掉该结点,并且还应该保证删除后得到的二叉树仍然满足二叉查找树的性质,即在二叉查找树中删除一个结点相当于删去有序序列中的一个结点。那么,如何在二叉查找树上删去一个结点呢? 如上页图所示:当被删结点是叶子或仅有一棵子树时,情况较简单,只是修改其双亲结点的指针就可以了;若被删结点既有左子树也有右子树时,应当如何

30、处理呢?假设在二叉查找树上被删结点为P(指向结点的指针为p),其双亲结点为F(结点指针为f),且不失一般性,可设p是f的左指针,即被删结点P是F的左孩子。一种处理方法如下页图所示:以被删结点的左子树中最大结点S(必然是叶子)的数据代替被删结点P的数据,然后删除叶子S。,Auxiliary Function to Remove One Node:,template Error_code Search_tree: remove_root(Binary_node* ,注意:sub_root 一定是引用参数,sub_root只有左 子树,以左孩子做为 删除后子树的新根,sub_root只有右 子树,以

31、右孩子做为 删除后子树的新根,sub_root既有左 子树,也有右子树. 搜寻它的左子树 中最大结点,令to_delete移动到 sub_root的左孩子,指针parent 保持跟踪to_delete 是它的双亲结点,在sub_root所指 结点的左子树中 搜寻最大结点 (此结点是它的前驱) 脱离循环to_delete 指向找到的结点,将to_delete所指结点 的数据域转移到 sub_root所指结点,If sub_root is NULL a code of not_present is returned. Otherwise, the root of the subtree is re

32、moved in such a way that the properties of a binary search tree are preserved. The parameter sub_root is reset as the root of the modified subtree, and success is returned.,if(parent=sub_root) sub_root -left=to_delete-left; else parent-right=to_delete-left; / end else(2) delete to_delete; return suc

33、cess; ,to_delete是sub_root 的左孩子它没有右子树, 因此,将to_delete所指结点 的左子树做为sub_root (parent)的左子树,将to_delete所指结点 的左子树做为parent的右子树,Remove to_delete from tree,Removal Method:,template Error_code Search_tree:remove(const Record ,Recursive function: search_and_destroy,template Error_code Search_tree: search_and_destr

34、oy(Binary_node* ,按target值向左(右)子树递归 调用搜寻被删结点.sub_root的 左(右)孩子域做为递归调用参数, 这样当到达边界调用remove_root时 sub_root的地址就可以由引用参数 带回到其双亲结点的左(右)孩子域,10.3 Building a Balanced Binary Search Tree,Problem: Start with an ordered list and build its entries into a binary search tree that is nearly balanced (bushy).,If the no

35、des of a complete binary tree are labeled in inorder sequence, starting with 1, then each node is exactly as many levels above the leaves as the highest power of 2 that divides its label.,由于课时不够,本节删略。 感兴趣的同学可以自学。 See Pg 463-472,10.4 Height Balance: AVL Trees,1.Denition: An AVL tree is a binary searc

36、h tree in which the heights of the left and right subtrees of the root differ by at most 1 and in which the left and right subtrees are again AVL trees. With each node of an AVL tree is associated a balance factor that is left higher, equal, or right higher according, respectively, as the left subtr

37、ee has height greater than, equal to, or less than that of the right subtree.,平衡因子,中文教材中,平衡因子左子树高度右子树高度;因此AVL定义为BST中任一结点平衡因子的绝对值 1。,平衡,左高1,左高2,右高2,enum Balance_factor left_higher, equal_height, right_higher ;,本教材中,将平衡因子定义为“枚举”类型。,AVL_node: pg.475,template struct AVL_node: public Binary_node Balance_

38、factor balance; AVL_node() balance = equal_height; left = right = NULL; AVL_node(const Record ,inherit,data member,constructor,constructor, In a Binary_node, left and right have type Binary_node*, so the inherited pointer members of an AVL node have this type too, not the more restricted AVL node *.

39、 In the insertion method,we must make sure to insert only genuine AVL nodes. The benefit of implementing AVL nodes with a derived structure is the reuse of all of our functions for processing nodes of binary trees and search trees., We often invoke these methods through pointers to nodes,such as lef

40、t-get_balance( ). But left could (for the compiler) point to any Binary_node, not just to an AVL_node, and these methods are declared only for AVL_node. A C+ compiler must reject a call such as left-get balance( ), since left might point to a Binary node that is not an AVL_node., To enable calls suc

41、h as left-get_balance( ), we include dummy versions of get_balance( ) and set_balance( ) in the underlying Binary_node structure. These do nothing:,template void Binary_node:set_balance(Balance_factor b) template Balance_factor Binary_node:get_balance(Balance_factor b) return equal_height; ,Class De

42、claration for AVL Trees,template class AVL_tree: public Search_tree public: Error_code insert(const Record ,Error_code remove_avl(Binary_node *,2.Insertions of a Node,See pg.478 Fig. 10.18 Simple insertions of nodes into an AVL tree,AVL insertions requiring rotations (pg.483 Fig.10.21),Public Insert

43、ion Method,template Error_code AVL_tree: insert(const Record ,Post: If the key of new_data is already in the AVL_tree, a code of duplicate_error is returned. Otherwise, a code of success is returned and the Record new_data is inserted into the tree in such a way that the properties of an AVL tree ar

44、e preserved. Uses: avl_insert.,Has the tree grown in height?,Recursive Function Specifications,template Error_code AVL_tree: avl_insert ( Binary_node * if (taller = true),Insert into empty subtree,duplicate_error,Insert in left subtree,Recursive call self,left subtree is taller,switch (sub_root-get_

45、balance() case left_higher: left_balance(sub_root); taller = false; break; case equal_height: sub_root-set_balance(left_higher); break; case right_higher: sub_root-set_balance(equal_height); taller = false; break; / end switch / end insert to left subtree (if block) else,Change balance factors,Left

46、subtree already Is taller,Re balancing always shortens the tree,Old left subtree Is equal height,left subtree Is taller,Insert in right subtree, result = avl_insert(sub_root-right, new_data, taller); if( taller = true ) switch(sub_root-get_balance() case left_higher: sub_root-set_balance(equal_heigh

47、t); taller = false; break; case equal_height: sub_root-set_balance(right_higher); break; case right_higher: right_balance(sub_root); taller = false; break; / end switch / end insert to right subtree (else block) return result; ,Old left subtree Is taller,ok!,Old left subtree Is equal height,right su

48、btree already Is taller,Rotations of an AVL Tree (pg.480 Fig.10.19),Rotations of an AVL Tree,template void AVL_tree: rotate_left(Binary_node * ,sub_root points to a subtree of the AVL_tree,This subtree has a non empty right subtree,impossible cases,impossible cases,The new balance factors for root a

49、nd right tree depend on the previous balance factor for sub tree:,Double Rotation,balance of an AVL Tree,template void AVL_tree: right_balance(Binary_node *,sub_root points to a subtree of an AVL_tree that is doubly unbalanced on the right,single rotation left,impossible cases,case left_higher: Bina

50、ry_node *sub_tree = right_tree-left; switch (sub_tree-get_balance() / switch(2) case equal_height: sub_root-set_balance(equal_height); right_tree-set_balance(equal_height); break; case left_higher: sub_root-set_balance(equal_height); right_tree-set_balance(right_higher); break; case right_higher: su

51、b_root-set_balance(left_higher); right_tree-set_balance(equal_height); break; / end switch(2),double rotation left,sub_tree-set_balance(equal_height); rotate_right(right_tree); rotate_left(sub_root); / end switch ,3.Removal of a Node,1. Reduce the problem to the case when the node x to be removed ha

52、s at most one child. 2. Delete x. We use a bool variable shorter to show if the height of a subtree has been shortened. 3. While shorter is true do the following steps for each node p on the path from the parent of x to the root of the tree. When shorter becomes false, the algorithm terminates.,4. C

53、ase 1: Node p has balance factor equal. The balance factor of p is changed according as its left or right subtree has been shortened, and shorter becomes false.,5. Case 2: The balance factor of p is not equal, and the taller subtree was shortened. Change the balance factor of p to equal, and leave s

54、horter as true.,6. Case 3: The balance factor of p is not equal, and the shorter subtree was shortened. Apply a rotation as follows to restore balance. Let q be the root of the taller subtree of p. 7. Case 3a: The balance factor of q is equal. A single rotation restores balance, and shorter becomes

55、false.,8. Case 3b: The balance factor of q is the same as that of p. Apply a single rotation, set the balance factors of p and q to equal, and leave shorter as true.,9. Case 3c: The balance factors of p and q are opposite. Apply a double rotation (rst around q , then around p), set the balance facto

56、r of the new root to equal and the other balance factors as appropriate, and leave shorter as true.,See pg.486 Fig. 10.22,See pg.487 Fig. 10.23,4. The height of an AVL Tree pg.485, The number of recursive calls to insert a new node can be as large as the height of the tree. At most one (single or do

57、uble) rotation will be done per insertion. A rotation improves the balance of the tree, so later insertions are less likely to require rotations. It is very difcult to nd the height of the average AVL tree,but the worst case is much easier. The worst-case behavior of AVL trees is essentially no wors

58、e than the behavior of random search trees. Empirical evidence suggests that the average behavior of AVL trees is much better than that of random trees, almost as good as that which could be obtained from a perfectly balanced tree.,Worst-Case AVL Trees, To find the maximum height of an AVL tree with

59、 n nodes, we instead find the minimum number of nodes that an AVL tree of height h can have. Let Fh be such a tree, with left and right subtrees Fl and Fr . Then one of Fl and Fr , say Fl , has height h - 1 and the minimum number of nodes in such a tree, and Fr has height h - 2 with the minimum number of nodes. These trees, as sparse

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论