Given the
root
of a binary tree, invert the tree, and return its root.
(給定一個二元樹,請翻轉整個樹)
TreeNode*
,傳入參數為 root
nullptr
swap
函數交換兩個左在Inorder中的順序是先將左子樹進行翻轉,再翻轉根結點,因此未翻轉的右子樹此時變成左子樹,我們要將左子樹再翻轉一次
Queue
來進行 level-order traversalclass Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
swap(root->left, root->right); // mid
invertTree(root->left); // left
invertTree(root->right); // right
return root;
}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
invertTree(root->left); // left
swap(root->left, root->right); // mid
invertTree(root->left); // right
return root;
}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
invertTree(root->left); // left
invertTree(root->right); // right
swap(root->left, root->right); // mid
return root;
}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* front = q.front();
q.pop();
swap(front->right, front->left);
if (front->left) q.push(front->left);
if (front->right) q.push(front->right);
}
}
return root;
}
};