题目
Leetcode 226. 翻转二叉树
代码(首刷自解)
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root)
return root;
auto tmp = root->left;
root->left = root->right;
root->right = tmp;
invertTree(root->left);
invertTree(root->right);
return root;
}
};
代码(8.16 二刷自解)
class Solution {
public:
TreeNode* Mirror(TreeNode* pRoot) {
if(!pRoot)
return pRoot;
swap(pRoot->left, pRoot->right);
Mirror(pRoot->left);
Mirror(pRoot->right);
return pRoot;
}
};
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return root
}
tmp := root.Left
root.Left = root.Right
root.Right = tmp
invertTree(root.Left)
invertTree(root.Right)
return root
}
代码(9.12 三刷自解)
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root)
return root;
if(!root->left && !root->right)
return root;
invertTree(root->left);
invertTree(root->right);
swap(root->left, root->right);
return root;
}
};