C++ recursive solution

  • 0

    This is a recursive solution for this exercice. If left and right node are NULL, return true, otherwise, the result is the compound of 3 conditions: the equality of value of left and right node, the value of left of left node and right of right node, and right of left node and left of right node.

    class Solution {
        bool test(TreeNode* nodeLeft, TreeNode* nodeRight){
            if (nodeLeft == NULL && nodeRight == NULL) return true;
            else if (!nodeLeft || !nodeRight) return false;
                return (nodeLeft->val == nodeRight->val) && test(nodeLeft->left, nodeRight->right) && test(nodeLeft->right, nodeRight->left);
        bool isSymmetric(TreeNode* root) {
            if (!root) return true;
            return test(root->left, root->right);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.