101. Symmetric Tree

来源:互联网 发布:win10优化不了怎么办 编辑:程序博客网 时间:2024/06/06 00:24

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 isSymmetric(TreeNode* root) {        if(!root){            return true;        }        reverse(root->left);        return __isSymmetric(root->left, root->right);            }        bool __isSymmetric(TreeNode* t1, TreeNode* t2){        if((!t1 && t2) || (t1 && !t2)){            return false;        }                if(!t1 && !t2){            return true;        }                if(t1->val != t2->val){            return false;        }                return __isSymmetric(t1->left, t2->left) && __isSymmetric(t1->right, t2->right);            }        void reverse(TreeNode* root){        if(!root){            return;        }        TreeNode* temp = root->left;        root->left = root->right;        root->right = temp;        reverse(root->left);        reverse(root->right);    }};

leetcode上的
bool isSymmetric(TreeNode *root) {        if (!root) return true;        return helper(root->left, root->right);    }        bool helper(TreeNode* p, TreeNode* q) {        if (!p && !q) {            return true;        } else if (!p || !q) {            return false;        }                if (p->val != q->val) {            return false;        }                return helper(p->left,q->right) && helper(p->right, q->left);     }