Check is Symmetric Tree

For example, this binary tree is symmetric:
    1
   / \
  2   2
 / \ / \
3  4 4  3
But the following is not:
    1
   / \
  2   2
   \   \
   3    3



/**
 * 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 SymmetricUtil(TreeNode *n1, TreeNode *n2) {
              if(n1 == nullptr && n2 == nullptr) return true;
              if(n1 == nullptr || n2 == nullptr) return false;
              if(n1->val != n2->val) return false;

              return SymmetricUtil(n1->left, n2->right) && SymmetricUtil(n1->right, n2->left);
       }

       bool isSymmetric(TreeNode *root) {
              // Start typing your C/C++ solution below
              // DO NOT write int main() function
              if(root == nullptr) return true;
              return SymmetricUtil(root->left, root->right);
       }
};

Comments

Popular posts from this blog

Unique Binary Search Trees

Coin in Line