[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.
这道题要求判断一棵二叉树是否对称。
如果一棵二叉树是对称的,则它的每一层结点从左到右都是对称的。利用层次遍历,当访问某一层时保留该层的所有结点,该层访问结束时,判断该层的结点是否对称。如果不对称,则二叉树不对称;否则,继续判断下一层。需要注意的是,无论当前结点的左右孩子是否为空,都要入队列。
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; }
相关文章推荐
- [Leetcode 101, Easy] Symmetric Tree
- leetcode 101 Symmetric Tree
- [leetcode.com]算法题目 - Symmetric Tree
- LeetCode: Symmetric Tree [101]
- leetcode[101]:Symmetric Tree
- LeetCode 101. Symmetric Tree
- LeetCode_Symmetric Tree
- [leetcode]Symmetric Tree
- LeetCode之Symmetric Tree
- leetcode-Symmetric Tree(2014.1.27)
- leetcode(101):Symmetric Tree
- [LeetCode]Symmetric Tree
- Leetcode-Symmetric Tree——判断二叉树是否对称
- [LeetCode]Symmetric Tree
- LeetCode101——Symmetric Tree
- [LeetCode] Symmetric Tree
- [leetcode] Symmetric Tree
- [LeetCode] - Symmetric Tree
- [leetcode] 101. Symmetric Tree
- leetcode--Symmetric Tree