226. 翻转二叉树
左子树给右子树,右子树给左子树
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr || (root->left == nullptr && root->right == nullptr))
return root;
TreeNode* left = invertTree(root->left);
TreeNode* right = invertTree(root->right);
root->left = right;
root->right = left;
return root;
}
};
101. 对称二叉树
挺经典的,有点没写出来,看了下题解
class Solution {
public:
// 左左和右右 左右和右左
bool check(TreeNode* left, TreeNode* right)
{
if (left == nullptr && right == nullptr) return true;
if (left == nullptr || right == nullptr) return false;
if (left->val != right->val) return false;
bool b1 = check(left->left, right->right);
bool b2 = check(left->right, right->left);
return b1 && b2;
}
bool isSymmetric(TreeNode* root) {
return check(root->left, root->right);
}
};