JZ18 二叉树的镜像

本文最后更新于:2022年4月9日 中午

image-20211006110654707

Solution

  • 迭代法,中序遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
// 中序遍历非递归 / 层序遍历也可以
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return TreeNode类
*/
TreeNode* Mirror(TreeNode* pRoot) {
// write code here
if (pRoot == nullptr) return nullptr;
stack<TreeNode *> stack;
TreeNode *node = pRoot;
while (node || !stack.empty()) {
while (node) {
stack.push(node);
node = node->left;
}
node = stack.top();
stack.pop();
swap(node->left, node->right);
node = node->left; // 翻转前的右子树
}
return pRoot;
}
};
  • 递归法,前/后序遍历
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
TreeNode* Mirror(TreeNode* pRoot) {
// write code here
if (pRoot == nullptr) return nullptr;
Mirror(pRoot->left);
Mirror(pRoot->right);
swap(pRoot->left, pRoot->right);
return pRoot;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!