题目如下:
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.
public boolean isSymmetric(TreeNode root) {
if(root==null || (root.right==null && root.left==null)){
return true;
}else if(root.right!=null && root.left!=null){
Stack<TreeNode> stack1 = new Stack<TreeNode>();
Stack<TreeNode> stack2 = new Stack<TreeNode>();
stack1.push(root.left);
stack2.push(root.right);
while(!stack1.empty() && !stack2.empty()){
TreeNode temp1 = stack1.pop();
TreeNode temp2 = stack2.pop();
if(temp1.val!=temp2.val){
return false;
}
if(temp1.right!=null&&temp1.left!=null&&temp2.right!=null&&temp2.left!=null){
stack1.push(temp1.left);
stack1.push(temp1.right);
stack2.push(temp2.right);
stack2.push(temp2.left);
}else if(temp1.right==null&&temp1.left!=null&&temp2.right!=null&&temp2.left==null){
stack1.push(temp1.left);
stack2.push(temp2.right);
}else if(temp1.right!=null&&temp1.left==null&&temp2.right==null&&temp2.left!=null){
stack1.push(temp1.right);
stack2.push(temp2.left);
}else if(temp1.right==null&&temp1.left==null&&temp2.right==null&&temp2.left==null){
}else{
return false;
}
}
return true;
}else{
return false;
}
}
这个题目是有Editoral Solution的,所以还是比较有意思的。Editoral Solution中介绍了一种递归的方法,一种迭代的方法,都是我之前没想到的,现在都贴到下面,首先是递归的方法:
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
public boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.val == t2.val)
&& isMirror(t1.right, t2.left)
&& isMirror(t1.left, t2.right);
}
然后是迭代的方法,用的数据结构是队列,代码如下:
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while (!q.isEmpty()) {
TreeNode t1 = q.poll();
TreeNode t2 = q.poll();
if (t1 == null && t2 == null) continue;
if (t1 == null || t2 == null) return false;
if (t1.val != t2.val) return false;
q.add(t1.left);
q.add(t2.right);
q.add(t1.right);
q.add(t2.left);
}
return true;
}
最后放上这道题Editoral Solution的地址,里面有问题解析和时间复杂度分析,地址如下:
https://leetcode.com/articles/symmetric-tree/
今天真是累死宝宝了,又跑了一天去办各种杂事,一想到明天还得6点多起来,感觉身体被掏空。