0226.Invert Binary Tree
Recursive #
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr) return nullptr;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
Stack #
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr) return nullptr;
stack<TreeNode*> sta;
sta.push(root);
while(!sta.empty()){
TreeNode* node = sta.top();
sta.pop();
swap(node->left, node->right);
if(node->right != nullptr) sta.push(node->right);
if(node->left != nullptr) sta.push(node->left);
}
return root;
}
};