LeetCode 226.翻转二叉树
题目链接:https://leetcode.cn/problems/invert-binary-tree/
题目
解答
将左右孩子换一下即可
递归法
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;
swap(root->left,root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
迭代法
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* cur = root;
if(cur != NULL) st.push(cur);
while(!st.empty()){
cur = st.top();
st.pop();
swap(cur->left,cur->right);
if(cur->left) st.push(cur->left);
if(cur->right) st.push(cur->right);
}
return root;
}
};
层序法
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
queue<TreeNode*> que;
if(root != NULL) que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0; i < size ; i++){
TreeNode* cur = que.front();
que.pop();
swap(cur->left,cur->right);
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
}
return root;
}
};