您的位置:首页 > 其它

[LeetCode]Symmetric Tree

2015-04-09 20:47 323 查看
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.

这道题要求判断一棵二叉树是否对称。

如果一棵二叉树是对称的,则它的每一层结点从左到右都是对称的。利用层次遍历,当访问某一层时保留该层的所有结点,该层访问结束时,判断该层的结点是否对称。如果不对称,则二叉树不对称;否则,继续判断下一层。需要注意的是,无论当前结点的左右孩子是否为空,都要入队列。

bool isSymmetric(TreeNode *root) {
        vector<TreeNode*> ans;
        if (!root)
            return true;
        queue<TreeNode*> q;
        q.push(root);
        int count = 1;
        int num = 0;
        while (!q.empty()){
            root = q.front();
            q.pop();
            count--;
            ans.push_back(root);
            if(root){
                q.push(root->left);
                q.push(root->right);
                num += 2;
            }
            if (count == 0){
                for (int i = 0, j = ans.size() - 1; i <= j; i++, j--){
                    if ((!ans[i] && !ans[j]) || (ans[i] && ans[j] && ans[i]->val == ans[j]->val))
                        continue;
                    else
                        return false;
                }
                count = num;
                num = 0;
                ans.resize(0);
            }
        }
        return true;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: