程序员面试题100题第11题——求二元查找树的镜像(即交换左右子树)

题目:求二元查找树的镜像(即交换左右子树),递归+迭代

分析:其实操作和前序二叉树类似。

void Mirror(TreeNode *root)//递归互换左右子树
{
    if(root == NULL)
        return ;

    TreeNode* p=root->leftChild;
    root->leftChild =root->rightChild;
    root->rightChild=p;

    //swap
    if(root->leftChild != NULL)
        Mirror(root->leftChild);
    if(root->rightChild != NULL)
        Mirror(root->rightChild);
}
void MirrorIteration(TreeNode *root)//迭代互换左右子树
{
    if(root == NULL)
        return ;
    stack<TreeNode*> stk;
    TreeNode* p;
    stk.push(root);

    while(!stk.empty())
    {
        p=stk.top();
        stk.pop();

        //swap
        TreeNode* temp=p->leftChild;
        p->leftChild =p->rightChild;
        p->rightChild=temp;
        //push
        if(p->leftChild != NULL)
            stk.push(p->leftChild);
        if(p->rightChild != NULL)
            stk.push(p->rightChild);
    }
}

 

posted @ 2012-10-02 17:13  logzh  阅读(216)  评论(0编辑  收藏  举报