- //节点的数据结构
- class BTree
- {
- public:
- int m_nValue;
- BTree* m_nLeft;
- BTree* m_nRight;
- public:
- BTree(int value)
- {
- m_nValue = value;
- }
- };
一:求二叉树的节点个数:
- /*
- 求二叉数中的节点个数
- 递归解法:
- 1:如果二叉树为空,节点的个数为0
- 2:如果二叉树不为空,二叉树节点的个数 = 左子树节点个数+右子树节点的个数+1;
- */
- int GetNodeCount(BTree* pRoot)
- {
- if (pRoot == NULL)
- return 0;
- int LeftNum = GetNodeCount(pRoot->m_nLeft);
- int RightNum = GetNodeCount(pRoot->m_nRight);
- int ret = LeftNum+RightNum+1;
- return ret;
- }
二:求二叉树的深度:
- /*
- 求二叉树的深度
- 递归解法:
- 1:如果二叉树为空,则二叉树的深度为0
- 2:如果二叉树不为空,二叉树的深度 = MAX(左子数深度,右子树深度)+1;
- */
- int GetTreeDepth(BTree* pRoot)
- {
- if (pRoot == NULL)
- return 0;
- int LeftDepth = GetTreeDepth(pRoot->m_nLeft);
- int RightDepth = GetTreeDepth(pRoot->m_nRight);
- int ret = max(LeftDepth,RightDepth)+1;
- return ret;
- }
三:四种遍历方式:
- /*
- 前序遍历:
- 1:如果二叉树为空,空操作
- 2:如果二叉树不为空,访问根节点,前序遍历左子树,前序遍历右子树
- */
- void PreOrderTraverse(BTree* pRoot)
- {
- if (pRoot == NULL)
- return;
- cout<<pRoot->m_nValue<<endl;
- PreOrderTraverse(pRoot->m_nLeft);
- PreOrderTraverse(pRoot->m_nRight);
- }
- /*
- 中序遍历:
- 1:如果二叉树为空,空操作
- 2:如果二叉树不为空,第一步中序遍历左字树,第二步访问跟节点,第三步中序遍历右子树
- */
- void InOrderTraverse(BTree* pRoot)
- {
- if (pRoot == NULL)
- return;
- InOrderTraverse(pRoot->m_nLeft);
- cout<<pRoot->m_nValue<<endl;
- InOrderTraverse(pRoot->m_nRight);
- }
- /*
- 后序遍历:
- 1:如果二叉树为空,空操作
- 2:如果二叉树不为空,第一步后序遍历左子树,第二步后序遍历右子树,第三步访问跟节点;
- */
- void BackOrderTraverse(BTree* pRoot)
- {
- if (pRoot == NULL)
- return;
- BackOrderTraverse(pRoot->m_nLeft);
- BackOrderTraverse(pRoot->m_nRight);
- cout<<pRoot->m_nValue<<endl;
- }
- /*
- 分层遍历二叉树(按层次从上到下,从左往右)
- 相当于广度优先搜素,使用队列实现。
- 队列初始化,将跟节点压入队列。
- 当队列不为空:弹出一个节点,访问,若左子树节点或者右子树节点不为空,将其压入队列!
- */
- void LevelTraverse(BTree* pRoot)
- {
- if (pRoot == NULL)
- return;
- queue<BTree*> q;
- q.push(pRoot);
- while (!q.empty())
- {
- BTree* pNode = q.front();
- q.pop();
- cout<<pNode->m_nValue<<endl;//访问节点
- if(pNode->m_nLeft != NULL)
- q.push(pNode->m_nLeft);
- if (pNode->m_nRight != NULL)
- q.push(pNode->m_nRight);
- }
- }