【剑指offer】二叉树的镜像

题目描述

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

举例:

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

二叉树的镜像:根据题目的描述,就是对于每一个结点,分别交换其左右孩子即可。EASY

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if(nullptr == pRoot)
            return;
        TreeNode* curPtr = nullptr;
        TreeNode* tempPtr = nullptr;
		std::stack<TreeNode*> s;
        s.push(pRoot);
        
        while(!s.empty())
        {
            curPtr = s.top();
            s.pop();
            if(nullptr != curPtr->left)
                s.push(curPtr->left);
            if(nullptr != curPtr->right)
                s.push(curPtr->right);
            tempPtr = curPtr->left;
            curPtr->left = curPtr->right;
            curPtr->right = tempPtr;
        }
    }
};

点赞