题目:
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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}"
.
题意:
就是判断一棵二叉树是否是对称的。
我还是采用非递归的方式,用两个队列LinkedList的方法,将每一棵二叉树的节点入队,然后依次判断。当然需要注意的是,碰到叶子节点的情况,很容易出现空指针错误。所以就需要注意,在if判断的时候要留个心眼儿。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public static boolean isSymmetric(TreeNode root)
{
if(root == null || ((root.left == null) && (root.right == null)))
return true;
else if((root.left != null && root.right == null ) || (root.left == null && root.right != null ))
return false;
else
{
LinkedList<TreeNode> nodeleft = new LinkedList<TreeNode>(); //用两个队列来分别遍历树的左右子树
LinkedList<TreeNode> noderight = new LinkedList<TreeNode>();
nodeleft.add(root);
noderight.add(root);
while(!nodeleft.isEmpty() && !noderight.isEmpty())
{
TreeNode left = nodeleft.peek();
TreeNode right = noderight.peek();
nodeleft.poll();
noderight.poll();
if((left.left == null && right.right != null ))
return false;
else if(left.left != null && right.right == null )
return false;
else if(left.left != null && right.right != null && left.left.val != right.right.val) //这里需要注意叶子节点
return false;
else if(left.right == null && right.left != null)
return false;
else if(left.right != null && right.left == null)
return false;
else if(right.left != null && left.right != null && left.right.val != right.left.val)
return false;
else
{
if((left == root) && (right == root))
{
if(left.left != null)
nodeleft.add(left.left);
if(right.right != null)
noderight.add(right.right);
}
else
{
if(left.left != null)
nodeleft.add(left.left);
if(left.right != null)
nodeleft.add(left.right);
if(right.right != null)
noderight.add(right.right);
if(right.left != null)
noderight.add(right.left);
}
}
}
return true;
}
}
}
这些题目都是树的典型应用,可以分别和之前做过的一些树的题目相比较,可以发现采用非递归的方法都是用LinkedList来模拟队列,然后让节点入队,依次比较节点之间的值的关系。