我们在前面的文章《图的广度优先搜索》中介绍了图的广度优先搜索算法,现在继续看一下相关的题目,以加深理解运用。
说明:下面题目中涉及到的tree的结构如下:
/*
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }*/
1.Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
这道题比较容易,遍历每一层,判断每一层是否对称即可。不过需要注意一点,我们在写BFS算法的时候,很多时候并不是严格的遍历完一行再遍历另一行,而是同时进行的。也就是说队列里面可能既有本层的节点,也有下一层的节点。
代码如下:
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.addLast(root);
ArrayList<TreeNode> r = new ArrayList<TreeNode>();
TreeNode tmp = null;
int len = 0;
while(true){
while(queue.size()>0){
tmp = queue.removeFirst();
r.add(tmp);
}
len = r.size();
for(int i = 0;i < len/2;i++){
if(r.get(i) == null && r.get(len-i-1) == null) continue;
else if(r.get(i) == null || r.get(len-i-1) == null) return false;
if(r.get(i).val != r.get(len-i-1).val) return false;
}
for(int i = 0;i < len; i++){
tmp = r.get(i);
if(tmp==null) continue;
queue.addLast(tmp.left);