二叉树是结点的有限集合, 该集合或者为空集, 或者是由一个根和两棵互不相交的称为该根的左子树和右子树的二叉树组成.
二叉树可以为空集, 可以有空二叉树, 也可以有空的左子树 或/和 又子树.
二叉树的性质: 1.第i层至多有2^(i - 1)个结点. 2.高度为h的二叉树上至多有2*h - 1个结点. 3.包含n个元素的二叉树高度至少为>=
log2(n + 1)取整. 3.任意一颗二叉树中, 若叶结点的个数为n0, 度为2的结点个数为n2, 则必有n0 = n2 + 1.
树与二叉树区别: 1.树不能为空树, 二叉树可以为空. 2.树的子树之间是无序的, 其子树不分次序. 二叉树中结点的子树要分左右子树.
满二叉树: 高度为h的二叉树恰好有2^h - 1个结点.
完全二叉树: 一棵二叉树中, 只有最下面两层结点的度可以小于2, 并且最下面一层的叶结点集中在靠左的若干位置上.
扩充二叉树(2 - 树): 除叶子结点外, 其余结点都必须有两个孩子.
二叉树类部分功能实现代码:
- #include "iostream"
- #include "cstdio"
- #include "cstring"
- #include "algorithm"
- using namespace std;
- template <class T>
- struct BTNode
- {
-
- BTNode() { lChild = rChild = NULL; }
- BTNode(const T& x) {
- element = x;
- lChild = rChild = NULL;
- }
- BTNode(const T& x, BTNode<T>* l, BTNode<T>* r) {
- element = x;
- lChild = rChild = NULL;
- }
- T element;
- BTNode<T>* lChild, rChild;
- };
- template <class T>
- class BinaryTree
- {
- public:
- BinaryTree() { root = NULL; }
- ~BinaryTree();
- bool IsEmpty() const;
- void Clear();
- bool Root(T& x) const;
- int Size();
- void MakeTree(const T& x, BinaryTree<T>& left, BinaryTree<T>& right);
- void BreakTree(T& x, BinaryTree<T>& left, BinaryTree<T>& right);
- void PreOrder(void (*Visit)(T& x));
- void InOrder(void (*Visit)(T& x));
- void PostOrder(void (*Visit)(T& x));
-
- protected:
- BTNode<T>* root;
- private:
- void Clear()(BTNode<T>* &t);
- void PreOrder(void (*Visit)(T &x), BTNode<T> *t);
- void InOrder(void (*Visit)(T &x), BTNode<T> *t);
- void PostOrder(void (*Visit)(T &x), BTNode<T> *t);
- };
- template <class T>
- bool BinaryTree<T>::Root(T &x) const
- {
- if(root) {
- x = root -> element;
- return true;
- }
- return false;
- }
- template <class T>
- void BinaryTree<T>::MakeTree(const T& x, BinaryTree<T>& left, BinaryTree<T>& right)
- {
- if(!root || &left == &right || left.root || right.root) return;
- x = root -> element;
- left.root = root -> lChild;
- right.root = root -> rChild;
- delete root;
- root = NULL;
- }
- template <class T>
- void BinaryTree<T>::PreOrder(void (*Visit)(T& x))
- {
- PreOrder(Visit, root);
- }
- template <class T>
- void BinaryTree<T>::PreOrder(void (*Visit)(T& x), BTNode<T>* t)
- {
- if(t) {
- Visit(t -> element);
- PreOrder(Visit, t -> lChild);
- PreOrder(Visit, t -> rChild);
- }
- }
- template <class T>
- int BinaryTree<T>::Size()
- {
- return Size(root);
- }
- template <class T>
- int BinaryTree<T>::Size(BTNode<T> *t)
- {
- if(!t) return 0;
- return Size(t -> lChild) + Size(t -> rChild) + 1;
- }
树与二叉树区别: 1.树不能为空树, 二叉树可以为空. 2.树的子树之间是无序的, 其子树不分次序. 二叉树中结点的子树要分左右子树.
版权声明:本文为博主原创文章,未经博主允许不得转载。