leetcode 101. symmetrical binary tree (search)

https://leetcode-cn.com/problems/symmetric-tree/

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3
/**
 * 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 dfs(TreeNode* root1,TreeNode* root2){
        if(root1==NULL&&root2!=NULL)return false;
        if(root2==NULL&&root1!=NULL)return false;
        if(root2==NULL&&root1==NULL)return true;
        if(root1->val!=root2->val)return false;
        if(!dfs(root1->left,root2->right))return false;
        if(!dfs(root2->left,root1->right))return false;
        return true;
    }
    bool isSymmetric(TreeNode* root) {
        if(root==NULL)return true;
        return dfs(root->left,root->right);
    }
};

 

Guess you like

Origin www.cnblogs.com/wz-archer/p/12525866.html