题目链接:https://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 [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
方法一:链表保存节点顺序
最初我用了两个链表保存左子树和右子树的值,在来比较,明显麻烦了一些。
AC 6ms 76% Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<TreeNode> left=new ArrayList();
private List<TreeNode> right=new ArrayList();
public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
left(root.left);
right(root.right);
int i=0,j=0;
if(left.size()!=right.size())
return false;
while(i<left.size()&&j<right.size()){
if(left.get(i)==null&&right.get(i)==null){
i++;
j++;
continue;
}
if(left.get(i)==null||right.get(i)==null)
return false;
if(left.get(i).val!=right.get(j).val)
return false;
i++;
j++;
}
return true;
}
public void left(TreeNode root){
if(root==null){
left.add(root);
return;
}
left.add(root);
left(root.left);
left(root.right);
}
public void right(TreeNode root){
if(root==null){
right.add(root);
return ;
}
right.add(root);
right(root.right);
right(root.left);
}
}
方法二:递归中直接比较
在递归方法里面传入两个待比较的左右root节点,
然后依次比较每一层及以下的节点是否相同。
AC 5ms 100% Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return helper(root,root);
}
public boolean helper(TreeNode t1,TreeNode t2){
if(t1==null&&t2==null)
return true;
if(t1==null||t2==null)
return false;
return t1.val==t2.val
&&helper(t1.left,t2.right)
&&helper(t1.right,t2.left);
}
}
方法三:队列,思路同递归法相似。
分别把左右待比较的root节点放进去,并依次取出来,注意顺序上不能错位,
如果先取左侧的,那么放子节点的时候也一定要先放左侧的子节点。
AC 6ms Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> queue=new LinkedList();
queue.add(root);
queue.add(root);
while(!queue.isEmpty()){
TreeNode t1=queue.poll();
TreeNode t2=queue.poll();
if(t1==null&&t2==null)
continue;
if(t1==null||t2==null)
return false;
if(t1.val!=t2.val)
return false;
queue.add(t1.left);
queue.add(t2.right);
queue.add(t1.right);
queue.add(t2.left);
}
return true;
}
}