C++实现二叉树的相应操作
2021-07-12 04:06
标签:二叉树的遍历 turn tree node amp scom main 二叉树 com 技术 1. 二叉树的遍历:先序(递归、非递归),中序(递归、非递归),后序(递归、非递归)。 2. 获取二叉树节点个数: 3. 判断二叉树是否为完全二叉树: 4. 求二叉树两个节点的最小公共祖先: 5. 二叉树的翻转: 6. 求二叉树第k层的节点个数: 7. 求二叉树中节点的最大距离(相距最远的两个节点之间的距离): 8. 判断二叉树是否为平衡二叉树: C++实现二叉树的相应操作 标签:二叉树的遍历 turn tree node amp scom main 二叉树 com 技术 原文地址:https://www.cnblogs.com/si-lei/p/9547016.html#include
//递归获取二叉树节点个数
int getNodeCount(BiTree *pRoot)
{
if (pRoot == nullptr)
{
return 0;
}
else
{
return getNodeCount(pRoot->pLeft) + getNodeCount(pRoot->pRight) + 1;
}
}
//判断二叉树是否为完全二叉树
bool isCompleteBiTree(BiTree *pRoot)
{
if (pRoot == nullptr)
{
return false;
}
else
{
queue
//求二叉树两个节点的最小公共祖先
bool findnode(BiTree *pRoot, BiTree *node) //判断节点是否在某个节点下
{
if (pRoot == nullptr || node == nullptr)
{
return false;
}
if (pRoot == node)
{
return true;
}
bool isfind = findnode(pRoot->pLeft, node);
if (!isfind)
{
isfind = findnode(pRoot->pRight, node);
}
return isfind;
}
BiTree *getParent(BiTree *pRoot, BiTree *pChild1, BiTree *pChild2)
{
if (pRoot == pChild1 || pRoot == pChild2)
{
return pRoot;
}
if (findnode(pRoot->pLeft, pChild1))
{
if (findnode(pRoot->pRight, pChild2))
{
return pRoot;
}
else
{
return getParent(pRoot->pLeft, pChild1, pChild2);
}
}
else
{
if (findnode(pRoot->pLeft, pChild2))
{
return pRoot;
}
else
{
return getParent(pRoot->pRight, pChild1, pChild2);
}
}
}
//二叉树的翻转
BiTree *revBiTree(BiTree *pRoot)
{
if (pRoot==nullptr)
{
return nullptr;
}
BiTree *leftp = revBiTree(pRoot->pLeft);
BiTree *rightp = revBiTree(pRoot->pRight);
pRoot->pLeft = rightp;
pRoot->pRight = leftp; //交换
return pRoot;
}
//求二叉树第K层的节点个数
int getLevelConut(BiTree *pRoot, int k)
{
if (pRoot == nullptr || k 1)
{
return 0;
}
if (k == 1)
{
return 1;
}
else
{
int left = getLevelConut(pRoot->pLeft, k - 1);
int right = getLevelConut(pRoot->pRight, k - 1);
return (left + right);
}
}
//求二叉树中节点的最大距离
struct res //用以递归间传递距离
{
int maxDistance = 0;
int maxDepth = 0;
};
res getMaxDistance(BiTree *pRoot)
{
if (pRoot == nullptr)
{
res r1;
return r1;
}
res leftr = getMaxDistance(pRoot->pLeft);
res rightr = getMaxDistance(pRoot->pRight);
res last; //最终结果
last.maxDepth = max(leftr.maxDepth + 1, rightr.maxDepth + 1);//求最大深度
last.maxDistance = max(max(leftr.maxDistance, rightr.maxDistance), leftr.maxDepth + rightr.maxDepth + 2);//求最大距离
return last;
}
//判断二叉树是否为平衡二叉树:
bool isAVL(BiTree *pRoot, int & depth) //需要引用来传递数据
{
if (pRoot == nullptr)
{
depth = 0;
return true;
}
int leftdepth = 0;
int rightdepth = 0;
bool left = isAVL(pRoot->pLeft, leftdepth);
bool right = isAVL(pRoot->pRight, rightdepth);
if (left && right && abs(leftdepth - rightdepth) 1)
{
depth = 1 + (leftdepth > rightdepth ? leftdepth : rightdepth);//深度
return true;
}
else
{
return false;
}
}