100
1 Chap 5. Binary Trees

Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

1

Chap 5. Binary Trees

Page 2: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

2

Binary Trees

A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees, called the left and right subtrees, which are disjoint from each other and from the root.

Page 3: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

3

Binary Tree Example

Notation: Node, children, edge, parent, ancestor, descendant, path, depth, height, level, leaf node, internal node, subtree.

Page 4: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

4

Full and Complete Binary Trees

Full binary tree: Each node is either a leaf or internal node with exactly two non-empty children.

Complete binary tree: If the height of the tree is d, then all leaves except possibly level d are completely full. The bottom level has all nodes to the left side.

Page 5: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

5

Full Binary Tree Theorem (1) 定理

Theorem: The number of leaves in a non-empty full binary tree is one more than the number of internal nodes.

Proof (by Mathematical Induction):

Base case: A full binary tree with 1 internal node must have two leaf nodes.

Induction Hypothesis: Assume any full binary tree Tcontaining n-1 internal nodes has n leaves.

Page 6: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

6

Full Binary Tree Theorem (2)

Induction Step: Given tree T with n internal nodes, pick internal node I with two leaf children. Remove I’s children, call resulting tree T’.

By induction hypothesis, T’ is a full binary tree with n leaves.

Restore I’s two children. The number of internal nodes has now gone up by 1 to reach n. The number of leaves has also gone up by 1.

Page 7: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

7

Full Binary Tree Corollary(推论)

Theorem: The number of null pointers in a non-empty tree is one more than the number of nodes in the tree.

Proof: Replace all null pointers with a pointer to an empty leaf node. This is a full binary tree.

Page 8: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

8

二叉树

的重要特性

Page 9: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

9

性 质 1

在二叉树的第i(i≥1)层上至多有

2i-1 个结点

Page 10: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

10

用归纳法证明

归纳基

归纳假设

归纳证明

i = 1 层时,只有一个根结点:

2i-1 = 20 = 1假设对所有的 j,1≤ j i时,命题成立。则第j (j=i-1)层最多有2i-2个结点。当j=i时,

二叉树上每个结点至多有两

棵子树,则第 i 层的结点数

≤ 2i-2 2 = 2i-1

Page 11: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

11

性 质 2

深度为k(k≥1)的二叉树上至多

含2k-1 个结点

Page 12: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

12

证明

基于上一条性质,深度为k的二叉

树上的结点数至多为

20+21+ +2k-1 = 2k-1

Page 13: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

13

性 质 3

对任何一棵二叉树,若它含有n0 个

叶子结点、n2 个度为2的结点,则必存

在关系式:n0 = n2+1

Page 14: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

14

证明

设二叉树上结点总数 n = n0 + n1 + n2又二叉树上分支总数 b = n1+2n2

而 b = n-1 = n0 + n1 + n2 - 1

由此, n0 = n2 + 1

Page 15: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

15

性 质 4

具有n个结点的完全二叉树的深度

为log2n +1

Page 16: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

16

证明

设完全二叉树的深度为 k

则根据第二条性质得 2k-1 ≤ n < 2k

即 k-1 ≤ log2 n < k

因为k只能是整数,因此,k=log2n +1

Page 17: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

17

Binary Tree Node Class (1)

// Binary tree node classtemplate <class Elem>class BinNodePtr : public BinNode<Elem> {private:

Elem it; // The node's valueBinNodePtr* lc; // Pointer to left childBinNodePtr* rc; // Pointer to right child

public:BinNodePtr() { lc = rc = NULL; }BinNodePtr(Elem e, BinNodePtr* l =NULL,

BinNodePtr* r =NULL){ it = e; lc = l; rc = r; }

Page 18: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

18

Binary Tree Node Class (2)

Elem& val() { return it; }void setVal(const Elem& e) { it = e; }inline BinNode<Elem>* left() const{ return lc; }

void setLeft(BinNode<Elem>* b){ lc = (BinNodePtr*)b; }

inline BinNode<Elem>* right() const{ return rc; }

void setRight(BinNode<Elem>* b){ rc = (BinNodePtr*)b; }

bool isLeaf(){ return (lc == NULL) && (rc == NULL); }

};

Page 19: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

19

Traversals (1)

Any process for visiting the nodes in some order is called a traversal.

Any traversal that lists every node in the tree exactly once is called an enumeration of the tree’s nodes.

Page 20: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

20

Traversals (2)

Preorder traversal: Visit each node before visiting its children.Postorder traversal: Visit each node after

visiting its children. Inorder traversal: Visit the left subtree,

then the node, then the right subtree.

Page 21: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

21

Traversals (3)

template <class Elem> // Good implementationvoid preorder(BinNode<Elem>* subroot) {

if (subroot == NULL) return; // Emptyvisit(subroot); // Perform some actionpreorder(subroot->left());preorder(subroot->right());

}

template <class Elem> // Bad implementationvoid preorder2(BinNode<Elem>* subroot) {

visit(subroot); // Perform some actionif (subroot->left() != NULL)preorder2(subroot->left());

if (subroot->right() != NULL) preorder2(subroot->right());

}

Page 22: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

22

Traversal Example

// Return the number of nodes in the treetemplate <class Elem>int count(BinNode<Elem>* subroot) {

if (subroot == NULL)return 0; // Nothing to count

return 1 + count(subroot->left())+ count(subroot->right());

}

Page 23: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

23

Binary Tree Implementation (1)

Page 24: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

24

Binary Tree Implementation (2)

Page 25: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

25

Union Implementation (1)enum Nodetype {leaf, internal};class VarBinNode { // Generic node classpublic:

Nodetype mytype; // Store type for nodeunion {struct { // nternal node

VarBinNode* left; // Left childVarBinNode* right; // Right childOperator opx; // Value

} intl;Operand var; // Leaf: Value only

};

Page 26: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

26

Union Implementation (2)// Leaf constructorVarBinNode(const Operand& val){ mytype = leaf; var = val; }

// Internal node constructorVarBinNode(const Operator& op,

VarBinNode* l, VarBinNode* r) {mytype = internal; intl.opx = op;intl.left = l; intl.right = r;

}bool isLeaf() { return mytype == leaf; }VarBinNode* leftchild(){ return intl.left; }

VarBinNode* rightchild(){ return intl.right; }

};

Page 27: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

27

Union Implementation (3)// Preorder traversalvoid traverse(VarBinNode* subroot) {if (subroot == NULL) return;

if (subroot->isLeaf())cout << "Leaf: “

<< subroot->var << "\n";else {cout << "Internal: “

<< subroot->intl.opx << "\n";traverse(subroot->leftchild());traverse(subroot->rightchild());

}}

Page 28: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

28

Inheritance (1)class VarBinNode { // Abstract base classpublic:

virtual bool isLeaf() = 0;};

class LeafNode : public VarBinNode { // Leafprivate:

Operand var; // Operand valuepublic:

LeafNode(const Operand& val){ var = val; } // Constructor

bool isLeaf() { return true; }Operand value() { return var; }

};

Page 29: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

29

Inheritance (2)

// Internal nodeclass IntlNode : public VarBinNode {private:

VarBinNode* left; // Left childVarBinNode* right; // Right childOperator opx; // Operator value

public:IntlNode(const Operator& op,

VarBinNode* l, VarBinNode* r){ opx = op; left = l; right = r; }

bool isLeaf() { return false; }VarBinNode* leftchild() { return left; }VarBinNode* rightchild() { return right; } Operator value() { return opx; }

};

Page 30: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

30

Inheritance (3)

// Preorder traversalvoid traverse(VarBinNode *subroot) {

if (subroot == NULL) return; // Emptyif (subroot->isLeaf()) // Do leaf nodecout << "Leaf: "

<< ((LeafNode *)subroot)->value()<< endl;

else { // Do internal nodecout << "Internal: "

<< ((IntlNode *)subroot)->value() << endl;

traverse(((IntlNode *)subroot)->leftchild());

traverse(((IntlNode *)subroot)->rightchild());

}}

Page 31: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

31

Composite (1)class VarBinNode { // Abstract base classpublic:

virtual bool isLeaf() = 0;virtual void trav() = 0;

};

class LeafNode : public VarBinNode { // Leaf private:

Operand var; // Operand valuepublic:

LeafNode(const Operand& val){ var = val; } // Constructor

bool isLeaf() { return true; }Operand value() { return var; }void trav() { cout << "Leaf: " << value()

<< endl; }};

Page 32: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

32

Composite (2)class IntlNode : public VarBinNode {private:

VarBinNode* lc; // Left childVarBinNode* rc; // Right childOperator opx; // Operator value

public:IntlNode(const Operator& op,

VarBinNode* l, VarBinNode* r){ opx = op; lc = l; rc = r; }

bool isLeaf() { return false; }VarBinNode* left() { return lc; } VarBinNode* right() { return rc; } Operator value() { return opx; }void trav() {cout << "Internal: " << value() << endl;if (left() != NULL) left()->trav();if (right() != NULL) right()->trav();

}};

Page 33: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

33

Composite (3)// Preorder traversalvoid traverse(VarBinNode *root) {

if (root != NULL)root->trav();

}

Page 34: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

34

Space Overhead (1)

From the Full Binary Tree Theorem:Half of the pointers are null.

If leaves store only data, then overhead depends on whether the tree is full.

Ex: All nodes the same, with two pointers to children:

Total space required is (2p + d)nOverhead: 2pn If p = d, this means 2p/(2p + d) = 2/3 overhead.

Page 35: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

35

Space Overhead (2)

Eliminate pointers from the leaf nodes:n/2(2p) p

n/2(2p) + dn p + dThis is 1/2 if p = d.

2p/(2p + d) if data only at leaves 2/3 overhead.

Note that some method is needed to distinguish leaves from internal nodes.

=

Page 36: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

36

Array Implementation (1)

Position 0 1 2 3 4 5 6 7 8 9 10 11Parent -- 0 0 1 1 2 2 3 3 4 4 5

Left Child 1 3 5 7 9 11 -- -- -- -- -- --Right Child 2 4 6 8 10 -- -- -- -- -- -- --Left Sibling -- -- 1 -- 3 -- 5 -- 7 -- 9 --

Right Sibling -- 2 -- 4 -- 6 -- 8 -- 10 -- --

Page 37: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

37

Array Implementation (1)

Parent (r) =

Leftchild(r) =

Rightchild(r) =

Leftsibling(r) =

Rightsibling(r) =

Page 38: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

线索化二叉树线索化二叉树

(Threaded Binary Tree)(Threaded Binary Tree)

Page 39: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

遍历二叉树的结果是,

求得结点的一个线性序列A

B

C

D

EF

G

H K

先序序列A B C D E F G H K

中序序列B D C A H G K F E

后序序列D C B H K G F E A

何谓线索二叉树?

Page 40: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

指向该线性序列中的“前驱”和“后继” 的指针,称作“线索”

与其相应的二叉树,称作 “线索二叉树”

包含 “线索” 的存储结构,称作 “线索链表”

A B C D E F G H K

^ D ^

C ^

^ B E ^ 利用原结点中的“空指针”存储“线索”

Page 41: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

对线索链表中结点的约定

在二叉链表的结点中增加两个标志域

LTag和RTag,并作如下规定:

若该结点的左子树不空,

则LTag=0, LChild域的指针指向其

左孩子;否则,LTag=1, LChild域的指针指

向其“前驱”。

Page 42: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

若该结点的右子树不空,

则RTag=0, RChild域的指针指向其

右孩子;

否则,RTag=1, RChild域的指针指

向其“后继”。

如此定义的二叉树的存储结构称作

“线索链表”

Page 43: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

总结:总结:

LTag LTag = 0, = 0, LChildLChild为为指针指针,,指向指向左孩子左孩子

LTagLTag = 1, = 1, LChildLChild为为线索线索,,指向指向前驱前驱

RTagRTag = 0, = 0, RChildRChild为为指针指针,,指向指向右孩子右孩子

RTagRTag = 1, = 1, RChildRChild为为线索线索,,指向指向后继后继

Page 44: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

猜一猜,是哪一种线索二叉树

Page 45: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

后序线索二叉树后序线索二叉树后序序列后序序列D B E C AD B E C A

前序线索二叉树前序线索二叉树前序序列前序序列A B D C EA B D C E

Page 46: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

带头结点的中序线索二叉树

Page 47: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

寻找当前结点寻找当前结点

在在中序中序下的下的后继后继

若无右子树,则为后继线索所指

结点;

否则为对其右子树进行中序遍历

时访问的第一个结点。

Page 48: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

if (pRTag==1) if (pRChild!=T.root)后继为 pRChild

else 无后继else //pRTag==0

if (pRChild!=T.root)后继为当前结点右

子树的中序下的第一个结点

else 出错情况

A

B

D E

C

F

H I

K

G

J

L

Page 49: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

寻找当前结点寻找当前结点

在在中序中序下的下的前趋前趋

若无左子树,则为前驱线索所指

结点;

否则为对其左子树进行中序遍历

时访问的最后一个结点。

Page 50: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

if (pLTag==1)if (pLChild!=T.root)前驱为pLChild

else 无前驱else //pLTag==0

if (pLChild!=T.root)前驱为当前结点左子树的中序下的最后一个结点

else 出错情况

A

B

D E

C

F

H I

K

G

J

L

Page 51: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

寻找当寻找当前结点前结点在在前序前序下的下的后后继继

Page 52: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

寻找当寻找当前结点前结点在在前序前序下的下的前前趋趋

Page 53: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

寻找当寻找当前结点前结点在在后序后序下的下的后后继继

Page 54: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

寻找当寻找当前结点前结点在在后序后序下的下的前前趋趋

Page 55: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

55

Binary Search Trees

BST Property: All elements stored in the left subtree of a node with value K have values < K. All elements stored in the right subtree of a node with value K have values >= K.

Page 56: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

56

BST ADT(1)// BST implementation for the Dictionary ADTtemplate <class Key, class Elem,

class KEComp, class EEComp>class BST : public Dictionary<Key, Elem,

KEComp, EEComp> {private:

BinNode<Elem>* root; // Root of the BSTint nodecount; // Number of nodes void clearhelp(BinNode<Elem>*);BinNode<Elem>*inserthelp(BinNode<Elem>*, const Elem&);

BinNode<Elem>*deletemin(BinNode<Elem>*,BinNode<Elem>*&);

BinNode<Elem>* removehelp(BinNode<Elem>*,const Key&, BinNode<Elem>*&);

bool findhelp(BinNode<Elem>*, const Key&, Elem&) const;

void printhelp(BinNode<Elem>*, int) const;

Page 57: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

57

BST ADT(2)public:

BST() { root = NULL; nodecount = 0; }~BST() { clearhelp(root); } void clear() { clearhelp(root); root = NULL;

nodecount = 0; }bool insert(const Elem& e) {root = inserthelp(root, e);nodecount++;return true; }

bool remove(const Key& K, Elem& e) {BinNode<Elem>* t = NULL;root = removehelp(root, K, t);if (t == NULL) return false;e = t->val();nodecount--;delete t;return true; }

Page 58: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

58

BST ADT(3)bool removeAny(Elem& e) { // Delete min valueif (root == NULL) return false; // EmptyBinNode<Elem>* t;root = deletemin(root, t);e = t->val();delete t;nodecount--;return true;

}bool find(const Key& K, Elem& e) const{ return findhelp(root, K, e); }

int size() { return nodecount; }void print() const {if (root == NULL)cout << "The BST is empty.\n";

else printhelp(root, 0);}

Page 59: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

59

BST Search

template <class Key, class Elem,class KEComp, class EEComp>

bool BST<Key, Elem, KEComp, EEComp>::findhelp(BinNode<Elem>* subroot,

const Key& K, Elem& e) const {if (subroot == NULL) return false; else if (KEComp::lt(K, subroot->val())) return findhelp(subroot->left(), K, e);

else if (KEComp::gt(K, subroot->val())) return findhelp(subroot->right(), K, e);

else { e = subroot->val(); return true; }}

Page 60: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

60

BST Insert (1)

Page 61: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

61

BST Insert (2)

template <class Key, class Elem,class KEComp, class EEComp>

BinNode<Elem>* BST<Key,Elem,KEComp,EEComp>::inserthelp(BinNode<Elem>* subroot,

const Elem& val) {if (subroot == NULL) // Empty: create nodereturn new BinNodePtr<Elem>(val,NULL,NULL);

if (EEComp::lt(val, subroot->val()))subroot->setLeft(inserthelp(subroot->left(),

val));else subroot->setRight(

inserthelp(subroot->right(), val));// Return subtree with node insertedreturn subroot;

}

Page 62: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

62

Remove Minimum Value

template <class Key, class Elem,class KEComp, class EEComp>

BinNode<Elem>* BST<Key, Elem,KEComp, EEComp>::

deletemin(BinNode<Elem>* subroot, BinNode<Elem>*& min) {

if (subroot->left() == NULL) {min = subroot;return subroot->right();

}else { // Continue leftsubroot->setLeft(

deletemin(subroot->left(), min));return subroot;

}}

Page 63: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

63

BST Remove (1)

Page 64: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

64

BST Remove (2)

template <class Key, class Elem,class KEComp, class EEComp>

BinNode<Elem>* BST<Key,Elem,KEComp,EEComp>::removehelp(BinNode<Elem>* subroot,

const Key& K, BinNode<Elem>*& t) {if (subroot == NULL) return NULL;else if (KEComp::lt(K, subroot->val()))subroot->setLeft(

removehelp(subroot->left(), K, t));else if (KEComp::gt(K, subroot->val()))subroot->setRight(

removehelp(subroot->right(), K, t));

Page 65: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

65

BST Remove (2)

else { // Found it: remove itBinNode<Elem>* temp;t = subroot;if (subroot->left() == NULL)

subroot = subroot->right();else if (subroot->right() == NULL)

subroot = subroot->left();else { // Both children are non-empty

subroot->setRight(deletemin(subroot->right(), temp));

Elem te = subroot->val();subroot->setVal(temp->val());temp->setVal(te);t = temp;

} }return subroot;

}

Page 66: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

66

Cost of BST Operations

Find:

Insert:

Delete:

Page 67: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

67

Heaps

Heap: Complete binary tree with the heap property:

Min-heap: All values less than child values.Max-heap: All values greater than child values.

The values are partially ordered.

Heap representation: Normally the array-based complete binary tree representation.

Page 68: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

68

Heap ADTtemplate<class Elem,class Comp> class maxheap{private:

Elem* Heap; // Pointer to the heap arrayint size; // Maximum size of the heapint n; // Number of elems now in heapvoid siftdown(int); // Put element in place

public:maxheap(Elem* h, int num, int max);int heapsize() const;bool isLeaf(int pos) const;int leftchild(int pos) const;int rightchild(int pos) const;int parent(int pos) const;bool insert(const Elem&);bool removemax(Elem&);bool remove(int, Elem&);void buildHeap();

};

Page 69: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

69

Building the Heap

(a) (4-2) (4-1) (2-1) (5-2) (5-4) (6-3) (6-5) (7-5) (7-6)(b) (5-2), (7-3), (7-1), (6-1)

Page 70: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

PARENT(i) = (i-1)/2; /*父结点*/LEFT = 2i+1; /* 左子结点 */RIGHT(i) = 2i+2; /* 右子结点 */

70

Page 71: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

71

Siftdown (1)

For fast heap construction:Work from high end of array to low end. Call siftdown for each item. Don’t need to call siftdown on leaf nodes.template <class Elem, class Comp>void maxheap<Elem,Comp>::siftdown(int pos) {

while (!isLeaf(pos)) {int j = leftchild(pos);int rc = rightchild(pos);if ((rc<n) && Comp::lt(Heap[j],Heap[rc]))

j = rc;if (!Comp::lt(Heap[pos], Heap[j])) return; swap(Heap, pos, j);pos = j;

}}

Page 72: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

72

Siftdown (2)

Page 73: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

73

Remove Max Value

template <class Elem, class Comp>bool maxheap<Elem, Comp>:: removemax(Elem& it) {

if (n == 0) return false; // Heap is emptyswap(Heap, 0, --n); // Swap max with endif (n != 0) siftdown(0);it = Heap[n]; // Return max valuereturn true;

}

Page 74: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

74

Priority Queues (1)

A priority queue stores objects, and on request releases the object with greatest value.

Example: Scheduling jobs in a multi-tasking operating system.

The priority of a job may change, requiring some reordering of the jobs.

Implementation: Use a heap to store the priority queue.

Page 75: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

75

Priority Queues (2)

To support priority reordering, delete and re-insert. Need to know index for the object in question.

template <class Elem, class Comp>bool maxheap<Elem, Comp>::remove(int pos,

Elem& it) {if ((pos < 0) || (pos >= n)) return false; swap(Heap, pos, --n);while ((pos != 0) && (Comp::gt(Heap[pos],

Heap[parent(pos)])))swap(Heap, pos, parent(pos));

siftdown(pos);it = Heap[n];return true;

}

Page 76: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

76

Huffman Coding Trees

ASCII codes: 8 bits per character. Fixed-length coding.

Can take advantage of relative frequency of letters to save space.

Variable-length coding

Build the tree with minimum external path weight.

Z K F C U D L E2 7 24 32 37 42 42 120

Page 77: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

哈 夫 曼 树 与哈 夫 曼 编 码

Page 78: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

设给出一段报文设给出一段报文

CAST CAST SAT AT A TASACAST CAST SAT AT A TASA字符集合是字符集合是 { C, A, S, T }{ C, A, S, T },各个字,各个字

符出现的频度符出现的频度((次数次数))是是 WW=={ 2, 7, 4, 5 }{ 2, 7, 4, 5 }若给每个字符以等长编码若给每个字符以等长编码

AA : 00 T : 10 C : 01 S : 11: 00 T : 10 C : 01 S : 11则总编码长度为则总编码长度为 ( 2+7+4+5 ) * 2 = 36( 2+7+4+5 ) * 2 = 36

问题引入:问题引入:

Page 79: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

若按各个字符出现的概率不同而给若按各个字符出现的概率不同而给予不等长编码,可望减少总编码长度予不等长编码,可望减少总编码长度

AA : 0 T : 10 C : 110 S : 111: 0 T : 10 C : 110 S : 111它的总它的总编码长度为编码长度为

7*1+5*2+( 2+4 )*3 = 357*1+5*2+( 2+4 )*3 = 35比等长编码的情形要短比等长编码的情形要短

Page 80: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

哈 夫 曼 树(Huffman Tree)(Huffman Tree)

与哈 夫 曼 编 码

Page 81: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

结点的路径长度

从根结点到该结点的路径上分

支的数目

结点间路径长度结点间路径长度((Path LengthPath Length))连接两结点的路径上的分支数连接两结点的路径上的分支数

Page 82: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

树的树的带权路径长度带权路径长度((Weighted Path Length,WPLWeighted Path Length,WPL))

树的各叶结点所带的权值与该树的各叶结点所带的权值与该结点到根的路径长度的乘积的结点到根的路径长度的乘积的和和

树的路径长度树中每个结点的路径长度之和

1

0

n

iii l(wWPL )

Page 83: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

在所有含n个叶子结点、并带相同

权值的m叉树中,必存在一棵其带权路

径长度取最小值的树,称为“最优树”,或“哈夫曼树” (Huffman Tree)(Huffman Tree)

Page 84: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

具有不同带权路径长度的二叉树

哈哈夫曼树中,权值大的结点离根最近夫曼树中,权值大的结点离根最近

Page 85: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

227 9 7 9

77 55

44

99

22

WPL(T)= 72+52+23+43+92 =60

WPL(T)= 74+94+53+42+21 =89

5544

Page 86: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

构造哈夫曼树构造哈夫曼树

((以二叉树为例以二叉树为例))

Page 87: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

根据给定的 n 个权值 {w1, w2, …,

wn},造 n 棵二叉树的集合

F = {T1, T2, … , Tn},

其中每棵二叉树中均只含一个带权

值为 wi 的根结点,其左、右子树为

空树;

(1)(1)

Page 88: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

在 F 中选取其根结点的权值为最

小的两棵二叉树,分别作为左、

右子树构造一棵新的二叉树,并

置这棵新的二叉树根结点的权值

为其左、右子树根结点的权值之

和;

(2)(2)

Page 89: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

从F中删去这两棵树,同时加入

刚生成的新树;

重复 (2)(2) 和 (3)(3) 两步,直至 F 中只

含一棵树为止。

(3)(3)

(4)(4)

Page 90: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

99

已知权值已知权值 W={ 5, 6, 2, 9, 7 }W={ 5, 6, 2, 9, 7 }

55 66 22 77

55 22

7766 99 77

66 77

131399

55 22

77

Page 91: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

66 77

131399

55 22

77

99

55 22

77

1616

66 77

1313

2929

Page 92: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

任何一个字符的编码都不是同一任何一个字符的编码都不是同一

字符集中另一个字符的编码的前缀。字符集中另一个字符的编码的前缀。

前缀编码前缀编码

利用哈夫曼树可以构造一种不等利用哈夫曼树可以构造一种不等

长的二进制编码,并且构造所得的长的二进制编码,并且构造所得的哈哈

夫曼编码夫曼编码是一种是一种最优前缀编码最优前缀编码,即使,即使

所传所传电文的总长度最短。电文的总长度最短。

Page 93: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

9

5 2

7

16

6 7

13

290

0 0

0

1

1 1

100 01 10

110 111

哈夫曼编码

Page 94: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

例:给定一组权值: {23, 15, 66, 07, 11, 45, 33, 52, 39, 26, 58}试构造一棵具有最小带权外部路径长度

的扩充4叉树, 要求该4叉树中所有内部结

点的度都是4, 所有外部结点的度都是0。这棵扩充4叉树的带权外部路径长度是多

少?

nn叉叉HuffmanHuffman树树((自学自学))

Page 95: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

【解答】权值个数n = 11,扩充4 叉树的内

结点的度都为4,而外结点的度都为0。设

内结点个数为n4,外结点个数为n0,则可

证明有关系n0 = 3 * n4 + 1。本题中n0 = 11≠3 * n4 +1,需要补2个权

值为0的外结点。此时内结点个数n4 = 4。仿照霍夫曼树的构造方法来构造扩充

4叉树,每次合并4个结点。

Page 96: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

00 00 77 1111 1515 2323 2626 3333 3939 4545 5252 5858 6666

00 00 77 1111

18181515 2323 2626

8282

3333 3939 4545 5252

1691695858 6666

375375

树的带权路径长度WPL = 644

Page 97: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

97

Huffman Tree Construction (1)

Page 98: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

98

Huffman Tree Construction (2)

Page 99: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

99

Assigning Codes

Letter

Freq Code

Bits

C 32D 42E 120F 24K 7L 42U 37Z 2

Page 100: Chap 5. Binary Treesswjx.scu.edu.cn/course/311036030/include/courseware/Lecture4.pdfChap 5. Binary Trees. 2 Binary Trees A binary tree is made up of a finite set of nodes that is either

100

Coding and Decoding

A set of codes is said to meet the prefix property if no code in the set is the prefix of another.

Code for DEED:

Decode 1011001110111101:

Expected cost per letter: