Symmetric Tree -- leetcode

来源:互联网 发布:阿里云登陆 编辑:程序博客网 时间:2024/06/16 11:10

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

Note:
Bonus points if you could solve it both recursively and iteratively.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.



/** * 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 isSymmetric(TreeNode *root) {        list<TreeNode *> queue;        queue.push_back(root);        int count = 1;        while (!queue.empty()) {                TreeNode *node = queue.front();                queue.pop_front();                if (node) {                        queue.push_back(node->left);                        queue.push_back(node->right);                }                count--;                if (!count) {                        list<TreeNode *>::iterator left = queue.begin();                        list<TreeNode *>::reverse_iterator right = queue.rbegin();                        for (int i=0; i<queue.size()/2; i++, left++, right++) {                                if (!*left && !*right)                                        continue;                                if (!*left || !*right)                                        return false;                                if ((*left)->val != (*right)->val)                                        return false;                        }                        count = queue.size();                }        }        return true;    }};

本算法基于广度优遍历。

将每一层放置在队列中后,进行类似回文的对比。

有些算法是将val值存入队列,不足之处,是需要定义一个特殊的整型值表示NULL结点。

本算法直接将结点指针存入队列,克服这个缺点。

且不需要在入口处判断root是否为空。


0 0