判断是否是对称树,镜像树的。
思路:先判断根节点,将其拆分成左右孩子节点两棵树。然后用深度优先搜索(其实跟回溯法没啥区别)判断这两棵树的对称位置是否一致即可。
/**
* Definition for a binary tree node.* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool check(TreeNode* left_root,TreeNode* right_root){
if(left_root==NULL && right_root==NULL){
return true;
}else if(left_root==NULL || right_root==NULL){
return false;
}else{
if(left_root->val==right_root->val){
return check(left_root->left,right_root->right)&&check(left_root->right,right_root->left);
}else{
return false;
}
}
}
bool isSymmetric(TreeNode* root) {
if(root==NULL) return true;
return check(root->left,root->right);
}
};