Symmetric Tree

Q:

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.

A:

保存当前处于哪一层,以及该节点应该处于满二叉树对应的位置。

/**
 * 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) {
        if (!root) return true;
        vector<pair<int, TreeNode*> > cur_nodes;
        cur_nodes.push_back(make_pair(0,root));
        int level = 0;
        while (!cur_nodes.empty()) {
            vector<pair<int, TreeNode*> > next_nodes;
            int len = cur_nodes.size();
            if (level != 0 && len % 2 != 0) return false;
            for (int i = 0; i < len / 2; ++i) {
                if (cur_nodes[i].second->val != cur_nodes[len - i - 1].second->val ||
                    cur_nodes[i].first + cur_nodes[len - i - 1].first + 1 != pow(2, level))
                    return false;
            }
                
            for (int i = 0; i < len; ++i) {
                if (cur_nodes[i].second->left) {
                    next_nodes.push_back(make_pair(cur_nodes[i].first*2, cur_nodes[i].second->left));
                }
                if (cur_nodes[i].second->right) {
                    next_nodes.push_back(make_pair(cur_nodes[i].first*2+1, cur_nodes[i].second->right));
                }
            }
            cur_nodes.swap(next_nodes);
            level++;
        }
        return true;
    }
};

 

posted @ 2013-07-07 18:26  dmthinker  阅读(139)  评论(0)    收藏  举报