标签:root roo binary 二叉树 辅助 剑指offer struct tmp ret
递归的先序遍历二叉树,交换每个节点的左右子节点,即可生成二叉树的镜像
/**
* 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 == nullptr) return nullptr;
TreeNode *tmp = root->left;
root->left = mirrorTree(root->right);
root->right = mirrorTree(tmp);
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) {
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;
}
};
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node == NULL) {
continue;
}
swap(node->left, node->right);
q.push(node->left);
q.push(node->right);
}
return root;
}
};
标签:root roo binary 二叉树 辅助 剑指offer struct tmp ret
原文地址:https://www.cnblogs.com/Trevo/p/12662574.html