Symmetric Tree

来源:互联网 发布:程序打包软件 编辑:程序博客网 时间:2024/06/04 00:54

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.

判断树是不是对称的,这边分别利用一个队列来记录下一层节点的情况,然后进行判断。特别注意空树和只有根节点的树这两种特殊情况!!!

还有就是对给的第二个例子的那种情况,左右进入队列都要进行判断!当然,也可以用栈来实现。

/** * 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;queue<TreeNode*>qleft;queue<TreeNode*>qright;if(root->left)   qleft.push(root->left);if(root->right)   qright.push(root->right);if(qleft.size()!=qright.size())    return false;while (!qleft.empty() && !qright.empty()){if (qleft.front()->val != qright.front()->val)return false;if (qleft.front()->left)qleft.push(qleft.front()->left);if (qright.front()->right)qright.push(qright.front()->right);if (qleft.size() != qright.size())return false;if (qleft.front()->right)qleft.push(qleft.front()->right);if (qright.front()->left)qright.push(qright.front()->left);qleft.pop();qright.pop();if (qleft.size() != qright.size())return false;}return true;}};



0 0
原创粉丝点击