【剑指offer】【树】27.二叉树的镜像
题目链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/
递归
递归的先序遍历二叉树,交换每个节点的左右子节点,即可生成二叉树的镜像
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(!root) return nullptr;
auto tmp = root -> left;
root -> left = mirrorTree(root -> right);
root -> right = mirrorTree(tmp);
return root;
}
};
辅助栈/队列(BFS)
利用栈或队列遍历树的所有节点,交换每个节点的左右子节点
时间复杂度:O(n)
空间复杂度:O(1)
栈
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
if (node == NULL) {
continue;
}
swap(node->left, node->right);
s.push(node->left);
s.push(node->right);
}
return root;
}
};
队列
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(!root) return root;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
auto tmp = q.front();
q.pop();
swap(tmp -> left, tmp -> right);
if(tmp -> left) q.push(tmp -> left);
if(tmp -> right) q.push(tmp -> right);
}
return root;
}
};
知识的价值不在于占有,而在于使用

浙公网安备 33010602011771号