Leetcode题目:Symmetric Tree

题目:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / 
  2   2
 /  / 
3  4 4  3

But the following is not:

    1
   / 
  2   2
      
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

题目解答:需要判断一棵树是不是对称的,其实就是比较左子树的左节点和右子树的右节点是否对称以及左子树的右节点和右子树的左节点是否对称。依旧使用递归来解决问题。

根据此,可以写出下面的代码:

/**
 * 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 isSymmetric(TreeNode* root) {
        if( (root == NULL) || (root -> left == NULL) && (root -> right == NULL) )
            return true;
        else if((root -> left != NULL) && ( root -> right != NULL) && (root -> left -> val == root -> right -> val) )
        {
            return judgeSymNode(root -> left,root -> right);
        }
        else
            return false;
    }
   
    bool judgeSymNode(TreeNode * leftNode,TreeNode *rightNode)
    {
        if((leftNode == NULL) && (rightNode == NULL))
            return true;
        else if((leftNode == NULL) || (rightNode == NULL))
            return false;
        else if(leftNode -> val != rightNode -> val)
            return false;
        else
        {
            return judgeSymNode(leftNode -> left,rightNode -> right) && judgeSymNode(leftNode -> right,rightNode -> left);
        }
    }
   
};