二叉树的镜像
利用栈实现
- void MirrorNonRecurively(BinaryTreeNode *pNode)
- {
- if(NULL == pNode)
- return;
- stack<BinaryTreeNode *> stackTreeNode;
- stackTreeNode.push(pNode);
- while(stackTreeNode.size()) //栈不为空时
- {
- BinaryTreeNode *pNode = stackTreeNode.top();
- stackTreeNode.pop();
- if(NULL != pNode->Left || NULL != pNode->Right) //交换左右子树位置
- {
- BinaryTreeNode *pTemp = pNode->Left;
- pNode->Left = pNode->Right;
- pNode->Right = pTemp;
- }
- if(NULL != pNode->Left)
- stackTreeNode.push(pNode->Left);
- if(NULL != pNode->Right)
- stackTreeNode.push(pNode->Right);
- }
- }
利用递归
void Mirror(TreeNode *pRoot) {
if(NULL!=pRoot)
{
TreeNode *temp=pRoot->left;
pRoot->left=pRoot->right;
pRoot->right=temp;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
}
二叉树第k层的节点个数
k=1,nums=1;
k>1时,节点个数为左子树的k-1层节点个数加上右子树的k-1层节点个数,利用递归
int numlevel(Binary *node,int k)
{
if(node==NULL||k==0)
return 0;
if(K==1)
return 1;
return numlevel(node->left,k-1)+numlevel(node->right,k-1)
}
利用栈实现二叉树的前序遍历:根->左子树->右子树
void preOder(binary *root)
{
if(root==NULL)
return ;
stack<binary *>stacknode;
while(root!=NULL||stacknode.empty()==false)
{
while(root)
{
stacknode.push(root);
cout<<root->data<<endl;
root=root->left;
}
if(root==NULL)
{
root=stacknode.top();
root=root->right;
}
}
}
利用栈实现二叉树的中序遍历:左子树->根->右子树
void MidOrder(binary *root)
{
if(root==NULL)
return ;
stack<binary *>stacknode;
while(root!=NULL||stacknode.empty()==false)
{
while(root!=NULL)
{
stacknode.push(root);
root=root->left;
}
if(root==NULL)
{
root=stacknode.top();
cout<<root->data<<endl;
stacknode.pop();
root=root->right;
}
}
}
后序遍历:左子树->右子树->根
利用两个栈:s1栈:根,左子树,右子树
s2:根,右子树,左子树
void LastOrdee(binary *root)
{
if(root==NULL)
return;
stack<binary *>s1;
stack<binary *>s2;
binary *node=root;
s1.push(node);//根压入s1
while(s1.empty()==false)
{
node=s1.top();
s1.pop();
s2.push(node);//第一次是根压入s2,后右,左
if(node->left)
s1.push(node->left);//左压入s1
if(node->right)
s1.push(node->right);//右压入s1
}
while(s2.empty()==false)
{
node=s2.top();
s2.pop();
cout<<bode->data<<endl;
}
}
层次遍历,一层一层输出,先入先出,按照队列实现
void LevelOrderTravel(BinaryTreeNode* root)
{ if (root == NULL)
return;
queue<BinaryTreeNode*> q;
q.push(root);
while (q.empty() == false)
{
root = q.front();
visit(root);
q.pop();
if (root->m_pLeft)
q.push(root->m_pLeft);
if (root->m_pRight)
q.push(root->m_pRight);
}
}