您的位置:首页 > 编程语言 > C语言/C++

C++算法之 求二叉树中叶子节点的个数 与 判断两棵二叉树是否结构相同

2015-01-06 14:50 806 查看
//叶子节点的个数

/*

(1)如果二叉树为空,返回0

(2)如果二叉树不为空且左右子树为空,返回1

(3)如果二叉树不为空,且左右子树不同时为空,返回左子树中叶子节点个数加上右子树中叶子节点个数

*/

int GetLeafNodeNum(BTree* root)
{
	if(root == NULL)
		return 0;
	if(root->m_pLeft == NULL && root->m_pRight == NULL)
		return 1;

	int LeafNumOfLeft = GetLeafNodeNum(root->m_pLeft);
	int LeafNumOfRight = GetLeafNodeNum(root->m_pRight);

	int ret = LeafNumOfLeft + LeafNumOfRight;

	return ret;

}




/*

判断量个二叉树的结构是否相同

1:如果两个二叉树都为空,那么返回true

2:如果一个二叉树为空,另外一个不为空,那么返回false

3:如果两个二叉树都不为空,那么如果它们的左子树和右子树的结果相同,返回true否则返回false

*/

bool isEqual(BTree*  root1, BTree* root2)
{
	if(root1 == NULL && root2 == NULL)
		return true;
	else if ((root1 == NULL && root2!= NULL)|| (root1 != NULL && root2 == NULL))
		return false;

	bool equalLeft = isEqual(root1->m_pLeft,root2->m_pLeft);
	bool equalRight = isEqual(root1->m_pRight,root2->m_pRight);

	return (equalLeft && equalRight);
}


完整测试代码:

// BTNumOfKLevel.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

class BTree
{
public:
int m_nValue;
BTree* m_pLeft;
BTree* m_pRight;

BTree(int m):m_nValue(m)
{
m_pLeft = m_pRight = NULL;
}

};
//二叉树的插入实现
void Insert(int value, BTree* &root)
{
if (root == NULL)
{
root = new BTree(value);
}
else if(value < root->m_nValue)
Insert(value,root->m_pLeft);
else if(value > root->m_nValue)
Insert(value,root->m_pRight);
else
;
}

//叶子节点的个数
/*
(1)如果二叉树为空,返回0
(2)如果二叉树不为空且左右子树为空,返回1
(3)如果二叉树不为空,且左右子树不同时为空,返回左子树中叶子节点个数加上右子树中叶子节点个数
*/
int GetLeafNodeNum(BTree* root) { if(root == NULL) return 0; if(root->m_pLeft == NULL && root->m_pRight == NULL) return 1; int LeafNumOfLeft = GetLeafNodeNum(root->m_pLeft); int LeafNumOfRight = GetLeafNodeNum(root->m_pRight); int ret = LeafNumOfLeft + LeafNumOfRight; return ret; }

/*
判断量个二叉树的结构是否相同
1:如果两个二叉树都为空,那么返回true
2:如果一个二叉树为空,另外一个不为空,那么返回false
3:如果两个二叉树都不为空,那么如果它们的左子树和右子树的结果相同,返回true否则返回false

*/

bool isEqual(BTree* root1, BTree* root2) { if(root1 == NULL && root2 == NULL) return true; else if ((root1 == NULL && root2!= NULL)|| (root1 != NULL && root2 == NULL)) return false; bool equalLeft = isEqual(root1->m_pLeft,root2->m_pLeft); bool equalRight = isEqual(root1->m_pRight,root2->m_pRight); return (equalLeft && equalRight); }

int _tmain(int argc, _TCHAR* argv[])
{
BTree* m_pRoot = new BTree(4);
Insert(3,m_pRoot);
Insert(6,m_pRoot);
Insert(1,m_pRoot);
Insert(2,m_pRoot);
Insert(5,m_pRoot);
Insert(8,m_pRoot);
Insert(7,m_pRoot);
Insert(10,m_pRoot);

BTree* m_pRoot2 = new BTree(4);
Insert(3,m_pRoot2);
Insert(6,m_pRoot2);
Insert(1,m_pRoot2);
Insert(2,m_pRoot2);
Insert(5,m_pRoot2);
Insert(8,m_pRoot2);
Insert(7,m_pRoot2);
Insert(10,m_pRoot2);

int count = GetLeafNodeNum(m_pRoot);
cout<<"叶子节点的个数为:"<<count<<endl;

cout<<"两个树的结构是否相同:"<<isEqual(m_pRoot,m_pRoot2);

getchar();
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: