bool _IsCompleteTree(Node *pRoot)
{
if (pRoot == nullptr)
returntrue;
queue<Node *> q;
Node *pCur = pRoot;
q.push(pCur);
bool flag = false;
while (!q.empty())
{
Node *pTop = q.front();
q.pop();
if (flag&&pTop->_pLeft || pTop->_pRight)
returnfalse;
if (pTop->_pLeft == nullptr&&pTop->_pRight != nullptr)
returnfalse;
if (pTop->_pLeft)
q.push(pTop->_pLeft);
if (pTop->_pRight)
q.push(pTop->_pRight);
else
flag = true;
}
returntrue;
}
3. 判断是否是二叉树的后续遍历
bool IsPostOrder(int sequence[], intlength)
{
if (sequence == nullptr || length <= 0)
returnfalse;
int root = sequence[length - 1];
int i = 0;
for (; i < length-1; ++i)
{
if (sequence[i]>root)
break;
}
int j = i;
for (; j < length - 1; ++j)
{
if (sequence[i] < root)
returnfalse;
}
bool left = true;
if (i>0)
left = IsPostOrder(sequence, i);
bool right = true;
if (i < length - 1)
right = IsPostOrder(sequence + i, length - i - 1);
return left&&right;
}
4. 打印二叉树中和为某一值的路径
void _FindPath(Node *pRoot, int expectData, int Sum, vector<int> &path)
{
Sum += pRoot->_data;
path.push_back(pRoot->_data);
bool isLeaf = pRoot->_pLeft == nullptr&&pRoot->_pRight == nullptr;
if (isLeaf&&Sum == expectData)
{
printf("find the path\n");
vector<int>::iterator it = path.begin();
for (; it != path.end(); it++)
{
printf("%d\t", *it);
}
printf("\n");
}
if (pRoot->_pLeft)
_FindPath(pRoot->_pLeft, expectData, Sum, path);
if (pRoot->_pRight)
_FindPath(pRoot->_pRight, expectData, Sum, path);
//递归退出时记得清理栈
path.pop_back();
}
5. 二叉搜索树转双向链表
//注意pre用引用void _ToList(Node *pRoot, Node *&pre)
{
if (NULL==pRoot)
return;
Node *cur = pRoot;
_ToList(pRoot->_pLeft,pre);
if (pre)
{
pre->_pRight = cur;
}
cur->_pLeft = pre;
pre = cur;
_ToList(pRoot->_pRight,pre);
}