剑指offer 面试题27 二叉树的镜像(递归与非递归实现)

1.题目

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

示例

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

 

2.思路

2.1 递归解法

1) 交换根节点的左右子树
2) 镜像左子树
3) 镜像右子树

2.2.1 非递归解法1

非递归思想一:我们按照广度遍历二叉树的顺序,逐个处理遍历的节点。当处理的当前节点,如果有子节点,我们交换它们的子节点,并且把它们的子节点入队列。处理完当前节点以后,我们下一次处理队首的节点。

广度遍历详见:LeetCode 102. Binary Tree Level Order Traversal 二叉树的层次遍历/广度优先遍历

              剑指offer 面试题32 从上到下打印二叉树

2.2.2 非递归解法2

非递归思想二:我们也可以按照前序遍历二叉树的顺序,非递归的实现二叉树的镜像操作,每遇到一个节点,判断当前节点是否有子节点,如果有子节点,我们交换其左右子节点,然后把非空子节点入。直到为空。

先序遍历详见:LeetCode 144. Binary Tree Preorder Traversal 二叉树的前序遍历

3.实现

3.1 递归实现

class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if(pRoot == nullptr)
            return;
        
        TreeNode* temp = pRoot->left;
        pRoot->left = pRoot->right;
        pRoot->right = temp;
        
        Mirror(pRoot->left);
        Mirror(pRoot->right);
    }
};

3.2.1 非递归实现1

class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if(pRoot == nullptr)
            return;
        queue<TreeNode*> q;
        q.push(pRoot);
        
        while(!q.empty())
        {
            TreeNode* node = q.front();
            q.pop();
            
            if(node->left != nullptr || node->right != nullptr)
            {
                TreeNode* temp = node->left;
                node->left = node->right;
                node->right = temp;
            }
            
            if(node->left != nullptr) q.push(node->left);
            if(node->right != nullptr) q.push(node->right);
        }
        
    }
};

3.2.2 非递归实现2

class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if(pRoot == nullptr)
            return;
        
        stack<TreeNode*> s;
        s.push(pRoot);
        
        while(!s.empty())
        {
            TreeNode* node = s.top();
            s.pop();
            
            if(node->left != nullptr || node->right != nullptr)
            {
                TreeNode* temp = node->left;
                node->left = node->right;
                node->right = temp;
            }
            
            if(node->left != nullptr) s.push(node->left);
            if(node->right != nullptr) s.push(node->right);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/u014128608/article/details/92850294