二叉树

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;
}

注:其中部分图像是截取《大话数据结构》这本书的,感谢老杜!!!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值