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

C++实现:

/**
 * 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 check(TreeNode *leftNode, TreeNode *rightNode)
    {
        if (leftNode == NULL && rightNode == NULL)
            return true;
            
        if (leftNode == NULL || rightNode == NULL||leftNode->val != rightNode->val)
            return false;
            
        return check(leftNode->left, rightNode->right) && 
            check(leftNode->right, rightNode->left);
    }
    
    bool isSymmetric(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (root == NULL)
            return true;
            
        return check(root->left, root->right);
    }
};

C实现:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
 bool check(struct TreeNode* left,struct TreeNode*right){
	 if(left==NULL&&right==NULL)return true;
	 if(left==NULL||right==NULL||left->val!=right->val)return false;
	 return check(left->left,right->right)&&check(left->right,right->left);
 }
 bool isSymmetric(struct TreeNode* root) {
	 if(root==NULL)return true;
	 return check(root->left,root->right);
}


你可能感兴趣的:(leetcode Symmetric Tree对称树的判断)