101. Symmetric Tree

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following [1,2,2,null,3,null,3] 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 mir(TreeNode *left, TreeNode *right) {
        if (left == NULL && right == NULL) return true;
        if (left == NULL && right != NULL) return false;
        if (left != NULL && right == NULL) return false;
        if (left->val == right->val){
            return mir(left->left,right->right) && mir(left->right,right->left);
        }
        else return false;
    }
    bool isSymmetric(TreeNode* root) {
        if (root == NULL) return true;
        return mir(root->left, root->right);
    }
};

 

posted on 2017-07-21 17:54  Beserious  阅读(113)  评论(0编辑  收藏  举报