zoukankan      html  css  js  c++  java
  • 镜像二叉树——剑指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;
        }
    };

    结果:

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

    非递归:

    递归:

     
     
     
     
  • 相关阅读:
    编程总结2
    编程总结1
    我的三位老师
    《秋季学期学习总结》
    CodeAction_beta02 斐波那契 (多维DP)
    bzoj3029 守卫者的挑战 (多维dp)
    修剪草坪 (单调队列)
    CF734F Anton and School (构造)
    CF359B Permutation (构造)
    CF989C A Mist of Florescence (构造)
  • 原文地址:https://www.cnblogs.com/charlesblc/p/8435097.html
Copyright © 2011-2022 走看看