1、二叉树
2、二叉树的特点
1)每个节点最多有两颗子树。
2)左子树与右子树是有顺序的。
3)树中需要区分左、右子树。
3、几种特殊的二叉树
1)满二叉树:在一棵二叉树中如果所有分支节点都存在左右子树,并且所有叶子都在同一层上。
2)完全二叉树
个人理解是:完全二叉树中的所有节点与具有同样深度的满二叉树,它们按照层序编号,相同的节点是一一对应的,且编号是连续的。就称之为完全二叉树。完全二叉树
满二叉树一定是一个完全二叉树,反之则不一定成立。
4、二叉树常用的性质
1)在二叉数的第i层最多有2^(i-1)个节点。
2)深度为K的二叉树最多有2^k-1个节点。
3)对于任何一颗二叉树T,如果其叶子节点数为n,度为2的节点个数为m,则n-m=1
5、二叉树的插入实现
需要说明的是:程序是遵循左>根>右利用链表实现的。最终的结果为:代码如下:
#pragma once
#include<memory>
template<class T>
class BinaryTree
{
struct TreeNode
{
T data;//节点数据
TreeNode* pleftChild;//左子节点
TreeNode* prightChild;//右子节点
};
public:
BinaryTree();
~BinaryTree();
void InsertNode(const T&insertData);//插入节点
private:
void _InsertNode(TreeNode**root, const T&insertDara);
TreeNode* pRoot;//根节点
};
template<class T>
BinaryTree<T>::BinaryTree()
{
pRoot = NULL;
}
template<class T>
BinaryTree<T>::~BinaryTree()
{
}
template<class T>
void BinaryTree<T>::InsertNode(const T&insertData)
{
_InsertNode(&pRoot, insertData);
}
template<class T>
void BinaryTree<T>::_InsertNode(TreeNode** pNode,const T& insertData)
{
TreeNode *root = *pNode;
if (!root)//当前节点不存在,为空
{
TreeNode* pNewNode = new TreeNode;//开辟一块新内存
memset(pNewNode, 0x00, sizeof(TreeNode));//将新节点中数据置为0
pNewNode->data = insertData;//将需要插入的数据作为新节点的数据
*pNode = pNewNode;//将新节点与树连接起来
}
else//当前节点不为空
{
if (insertData>root->data)//大于在左子树
{
_InsertNode(&(root->pleftChild), insertData);
}
if (insertData<root->data)//小于在右子树
{
_InsertNode(&(root->prightChild), insertData);
}
}
}
主函数为:
#include "stdafx.h"
#include"BinaryTree.h"
int _tmain(int argc, _TCHAR* argv[])
{
BinaryTree<int>tree;
tree.InsertNode(45);
tree.InsertNode(23);
tree.InsertNode(90);
tree.InsertNode(87);
tree.InsertNode(14);
tree.InsertNode(99);
tree.InsertNode(35);
tree.InsertNode(55);
tree.InsertNode(77);
tree.InsertNode(91);
return 0;
}
注:其中部分图像是截取《大话数据结构》这本书的,感谢老杜!!!