[leetcode]101.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
解法一
思路
上来直接采用Same Tree的第二种解法,思路一模一样。
代码
/**
* 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) {
if(root == null) return true;
Deque<TreeNode> queue = new LinkedList<>();
queue.addLast(root.left);
queue.addLast(root.right);
while(!queue.isEmpty()){
TreeNode l = queue.removeFirst();
TreeNode r = queue.removeFirst();
if(l == null && r == null) continue;
else if(l == null || r == null || l.val != r.val)
return false;
else {
queue.addLast(l.left);
queue.addLast(r.right);
queue.addLast(l.right);
queue.addLast(r.left);
}
}
return true;
}
}
解法二
思路
递归的方法,一开始没有想出来,看了别人的解答发现构造一个辅助函数就容易理解很多。直接看代码就能理解思路。
代码
/**
* 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) {
if(root == null) return true;
return isMirror(root.left, root.right);
}
public boolean isMirror(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null || q.val != p.val)
return false;
return isMirror(p.left, q.right) && isMirror(p.right, q.left);
}
}