WEEK 5
- In a tree, the order of children does not matter. But in a binary tree, left child and right child are different.
Properties of Binary Trees
- The maximum number of nodes on level \(i\) is \(2^{i-1},i\geq1\).
- The maximum number of nodes in a binary tree of depth \(k\) is \(2^k-1,k\geq1\).
- For any nonempty binary tree, \(n_0 = n_2 + 1\) where \(n_0\) is the number of leaf nodes and \(n_2\) is the number of nodes of degree 2.
proof: 假设该二叉树总共有n个结点(\(n =n_0+n_1+n_2\)),则该二叉树总共会有n-1条边,度为2的结点会延伸出两条边,
同理,度为1的结点会延伸出一条边,则可列公式:$n-1 = 2n_2 + n_1 $,
合并两个式子可得:\(2n_2 + n_1 +1 =n_0 + n_1 + n_2\) ,则计算可知 \(n_0=n_2+1\)
3.3 Binary Search Trees
[Definition] A binary search tree is a binary tree. It may be empty. If it is not empty, it satisfies the following properties:
- 每个结点有一个互不不同的值
- 若左子树非空,则左子树上所有结点的值均小于根结点的值
- 若右子树非空,则右子树上所有结点的值均大于根结点的值
- 左、右子树也是是一棵二叉查找树
ADT
- Objects : A finite ordered list with zero or more elements.
- Operations :
- SearchTree MakeEmpty( SearchTree T )
- Position Find( ElementType X, SearchTree T )
- Position FindMin( SearchTree T )
- Position FindMax( SearchTree T )
- SearchTree Insert( ElementType X, SearchTree T )
- SearchTree Delete( ElementType X, SearchTree T )
- ElementType Retrieve( Position P )
Implementations
- Find
- \(T(N)=S(N)=O(d)\) where \(d\) is the depth of X
Iterative program :
Text Only | |
---|---|
- FindMin
Text Only | |
---|---|
- FindMax
Text Only | |
---|---|
- Insert
- 内存越界后不会马上报错,在下一次free或malloc时会失败
- Handle duplicated keys
-
\(T(N)=O(d)\)
-
Delete
-
Delete a leaf node : Reset its parent link to NULL
- Delete a degree 1 node : Replace the node by its single child
- Delete a degree 2 node : 用左子树最大值结点或右子树最小值结点替换
- \(T(N)=O(d)\)
Note : If there are not many deletions, then lazy deletion may be employed: add a flag field to each node, to mark if a node is active or is deleted. Therefore we can delete a node without actually freeing the space of that node. If a deleted key is reinserted, we won’t have to call malloc again.
-
Average-Case Analysis
-
The average depth over all nodes in a tree is \(O(logN)\) on the assumption that all trees are equally likely.
- 将\(n\)个元素存入二叉搜索树,树的高度将由插入序列决定
The correct answer is A.