101. Symmetric Tree

 C++ | 100% Success | Recursion | Easy Understanding

 

/**

 * 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 {

public:

    bool isSameTree(TreeNode* p, TreeNode* q) {

        if(p==NULL && q==NULL)

            return true;

        if(p==NULL && q!=NULL || (p!=NULL && q==NULL))

            return false;

       

        bool l = isSameTree(p->right,q->left);

        bool r = isSameTree(p->left,q->right);

        bool d= p->val==q->val;


        return l&&r&&d;

    }

    

    bool isSymmetric(TreeNode* root) {

        return isSameTree(root->left , root->right);

    }

};

Comments

Popular posts from this blog

1431. Kids With the Greatest Number of Candies

125. Valid Palindrome

771. Jewels and Stones