LeetCode 101. Symmetric Tree

来源:互联网 发布:如何做好淘宝 编辑:程序博客网 时间:2024/05/21 00:14

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.

recursively:用left->right和right->left比较,用left->left和right->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 symmetric(TreeNode* left, TreeNode* right){        if(!left && !right) return true;        if(left && right && left->val == right->val){            return symmetric(left->left, right->right) && symmetric(left->right, right->left);        }        return false;    }    bool isSymmetric(TreeNode* root) {        if(!root) return true;        return symmetric(root->left, root->right);    }};
iteratively:BFS

/** * 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;        queue<TreeNode*> q1;        queue<TreeNode*> q2;        vector<TreeNode*> v;        q1.push(root);        while(!q1.empty()){            TreeNode* node = q1.front();            q1.pop();            q2.push(node);            if(q1.empty()){                while(!q2.empty()){                    TreeNode* node = q2.front();                    q2.pop();                    v.push_back(node);                    if(node){                        q1.push(node->left);                        q1.push(node->right);                    }                }                int i = 0, j = v.size() - 1;                while(i < j){                    if(!v[i] && !v[j]){                        i ++;                        j --;                    }else if(!v[i] && v[j] || v[i] && !v[j]) return false;                    else if(v[i]->val == v[j]->val){                        i ++;                        j --;                    }else return false;                }                v.clear();                            }        }        return true;            }};



0 0