【easy】101. Symmetric Tree

判断一棵二叉树是否对称

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

 

posted @ 2018-02-12 22:00  Sherry_Yang  阅读(92)  评论(0编辑  收藏  举报