剑指offer 二叉树的镜像

  • 题目描述

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

  • 递归解法
class Solution {
public:
    void Mirror(TreeNode *pRoot) {
		if (pRoot != NULL){
			TreeNode *p = pRoot->left;
			pRoot->left = pRoot->right;
			pRoot->right = p;
			Mirror(pRoot->left);
			Mirror(pRoot->right);
		}
    }
};
  • 非递归解法

巧妙地借助栈来实现非递归算法。

class Solution {
public:
    void Mirror(TreeNode *pRoot) {
		if (pRoot != NULL){
			stack<TreeNode*> s;
			s.push(pRoot);
			while (!s.empty()){
				TreeNode* t = s.top();
				s.pop();
				if (t->left != NULL || t->right != NULL){
					TreeNode* p = t->left;
					t->left = t->right;
					t->right = p;
				}
				if (t->left)
					s.push(t->left);
				if (t->right)
					s.push(t->right);
			}
		}
    }
};
弹钢琴的猫 /
Published under (CC) BY-NC-SA in categories 算法  tagged with 剑指offer  Tree