镜像二叉树——剑指Offer

https://www.nowcoder.net/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tqId=11171&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。
 

思路:

我用了两种方法,一种是递归的(Mirror2),一种是非递归的,也就是用栈实现的先序遍历(Mirror)。
 

代码:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
    void switchChild(TreeNode *pNode) {
        if (pNode == NULL) return;
        TreeNode *tmp = pNode->left;
        pNode->left = pNode->right;
        pNode->right = tmp;
    }
public:
    void Mirror(TreeNode *pRoot) {
        // non recursive, any iterate, and change child
        stack<TreeNode *> stk;
        
        if (pRoot == NULL) return;
        stk.push(pRoot);
        
        while (!stk.empty()) {
            TreeNode *tmp = stk.top();
            stk.pop();
            switchChild(tmp);
            if (tmp->left) stk.push(tmp->left);
            if (tmp->right) stk.push(tmp->right);
        }
        
    }
    
    void Mirror2(TreeNode *pRoot) {
        // recursive
        if (pRoot == NULL) return;
        Mirror(pRoot->left);
        Mirror(pRoot->right);
        TreeNode *tmp = pRoot->left;
        pRoot->left = pRoot->right;
        pRoot->right = tmp;
    }
};

结果:

一模一样快。可能因为非递归实现的也是先序,用了栈,其实和递归程序的逻辑是一样的。

非递归:

递归:

 
 
 
 
原文地址:https://www.cnblogs.com/charlesblc/p/8435097.html