【树】[递归的典型] leetcode_226_翻转二叉树
递归-前序-后序都行,中序的话(左翻转,中翻转的时候会把左再翻一遍,所以不行),层序也行。
前序递归:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr){
return root;
}
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
前序迭代:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
stack<TreeNode*> s_node;
TreeNode *cur = root;
while(!s_node.empty() || cur!=nullptr){
while(cur != nullptr){
s_node.push(cur);
swap(cur->left, cur->right);//第一次遇见的地方,交换左右
cur = cur->left;
}
cur = s_node.top();
s_node.pop();
cur = cur->right;
}
return root;
}
};
层序:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) return nullptr;
TreeNode *cur = root;
queue<TreeNode*> q_node;
q_node.push(cur);
while(!q_node.empty()){
int si = q_node.size();
for (int i = 0; i < si; i++){
cur =q_node.front();
swap(cur->left, cur->right);
q_node.pop();
if (cur->left){
q_node.push(cur->left);
}
if (cur->right){
q_node.push(cur->right);
}
}
}
return root;
}
};