Binary Tree
基本概念
- root 根节点;node 节点;edge 边;
- subtree 包含left和right
- parents and children
- ancestor and desendant:如果A到B之间自上而下存在唯一一条路径,那么A是B的ancestor,B是A的descendant。
- path:根节点至任意一个节点存在唯一一条路径,路径的边数称为length,一个节点对应的路径长度称为它的depth(基数词),对应它的level(基数词)。
- height = largest depth + 1
- leaf node(no children),internal node(have children)
- full binary tree:每个节点要么是有两个children,要么是leaf node(不存在只有一个子节点的节点)
- full binary tree theorem: the number of leaves in a non-empty full Binary Tree is one more than the number of internal nodes
- corollary: the number of empty subtrees in a non-empty Binary Tree is one more than the number of Binary Tree nodes.
- complete binary tree:除了叶节点所在的level都是满的(所有的叶节点在一个level),starting at the root and filled by levels from left to right
Traversal 遍历法
- preorder: node => left child => right child
- postorder: left child => right child => node
- inorder:left child => node => right child
Binary Search Tree 二叉搜索树
基本性质
- left subtree with key values < < < self key value
- right subtree with key values ≥ \geq ≥ self key value
基本操作
- insert & search 按照性质来做
- remove 操作
- leaf node:不需要什么额外操作
- internal node with only one child: 把它的子节点和父节点链接起来
- internal node with both children: 找出它右边子树的最小值来代替
Heap 堆内存
基本性质
- min-heap: parent<children
- max-heap: parent>children
- Heap 是 complete binary tree 且是 array-based implementation.
基本操作(以min-heap举例)
- siftdown:如果父节点的值大于其中一个子节点的值那么父节点与那个子节点交换
- siftup:如果子节点的值小于父节点的值,那么和它交换
- insert:先加到最后,再做siftup
- remove:和最后一个元素交换,然后删掉,并对最后一个元素做siftdown
- initialisation:先把所有元素填到一个表中,然后从最后一个元素的parent开始做siftdown,一直做到root(叫做backward iterated siftdown)
补充:C++中的左值和右值的含义
- 左值:表达式结束时依然存在的持久对象
- 右值:表达式结束时不再存在的临时对象
- move函数