版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38088298/article/details/86660572
- 描述:操作给定的二叉树,将其变换为源二叉树的镜像。
源二叉树:
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树:
8
/ \
10 6
/ \ / \
11 9 7 5
- 分析:所谓二叉树镜像是交换每个节点的左右子树得到的新树,实质上考察的是二叉树的遍历,遍历到一个节点就交换这个节点的子树,既然是遍历树,那么就有如下两种方式。
- 思路一:先序递归遍历。
/*
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 (pRoot) {
swap(pRoot -> left, pRoot -> right);
Mirror(pRoot -> left);
Mirror(pRoot -> right);
}
}
};
- 思路二:非递归先序遍历。
/*
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 (pRoot == NULL) return;
stack<TreeNode*> TNode;
TNode.push(pRoot);
while (!TNode.empty()) {
TreeNode* temp = TNode.top();
TNode.pop();
swap(temp -> left, temp -> right);
//标准先序遍历,先压入右节点
if (temp -> right != NULL) TNode.push(temp -> right);
if (temp -> left != NULL) TNode.push(temp -> left);
}
}
};