这个方法略2,新博文地址:[leetcode]Symmetric Tree
http://oj.leetcode.com/problems/symmetric-tree/
写道
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.
判断树是否是对称的。要求用递归和循环实现。
我对这道题大概有三种思想:
1. 层次遍历,判断每一层是否是对称的(循环思想)
2. 生成该树的镜像,判断是否跟其镜像相同(麻烦点,树的镜像和判断两棵树是否相同两个知识点)
3. 递归实现(网上基本上都是递归算法,代码我也懒得写了,直接粘过来了)
我写的是层次遍历的思想,比较直观,但是代码比较乱
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
queue.offer(root);
int numCount = 1;//表示当前层的节点数
while (!queue.isEmpty()) {
String[] sList = new String[numCount * 2];//存储该层的节点val
int index = 0;
int levelNodeCount = 0;//临时变量,记录下一层的节点数
for (int i = 0; i < numCount; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
levelNodeCount++;
sList[index++] = String.valueOf(node.left.val);
} else {
sList[index++] = "#";
}
if (node.right != null) {
queue.offer(node.right);
levelNodeCount++;
sList[index++] = String.valueOf(node.right.val);
} else {
sList[index++] = "#";
}
}
numCount = levelNodeCount;
index --;//sList的长度
for(int i = 0; i <= index /2; i++){//判断该层节点是否对称
if(!sList[i].equals(sList[index - i])){
return false;
}
}
}
return true;
}