LeetCode 101 Symmetric Tree DFS
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Solution
判断树是否为对称的。我们可以直接对左右子树进行 \(DFS\) 递归
点击查看代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
bool check(TreeNode* LeftRoot, TreeNode* RightRoot){
if(!LeftRoot && !RightRoot) return true;
else if(!LeftRoot || !RightRoot) return false;
if(LeftRoot->val != RightRoot->val) return false;
return check(LeftRoot->right, RightRoot->left) && check(LeftRoot->left, RightRoot->right);
}
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return check(root->left, root->right);
}
};