首页 > 代码库 > Symmetric Tree

Symmetric Tree

问题:判断二叉树是否为镜像二叉树
分析:递归判断,根节点单独判断,然后递归左结点和右结点,之后每次一起递归左结点的左结点和右结点的右结点比较,左结点的右结点和右结点的左结点比较

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool dfs(TreeNode *left,TreeNode *right)    {        if(!left && !right) return true;//需要先判断这个,不然val那个可能会出现RE        if((left && !right) || (!left && right) || (left->val!=right->val)) return false;        return dfs(left->left,right->right) && dfs(left->right,right->left);    }    bool isSymmetric(TreeNode *root) {        if(root==NULL || (!root->left && !root->right)) return true;        return dfs(root->left,root->right);    }};