前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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 class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return isSymmetric(root.left,root.right);
}
public boolean isSymmetric(TreeNode root1,TreeNode root2){
if(root1 == null && root2 == null) return true;
if(root1 != null && root2 != null){
boolean flag = root1.val == root2.val;
if(flag) flag = isSymmetric(root1.left,root2.right);
if(flag) flag = isSymmetric(root1.right,root2.left);
return flag;
}
return false;
}
}然并卵,不知道怎么体现的。
Your runtime beats 4.64% of java submissions.
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
Stack<TreeNode> stack1 = new Stack<TreeNode>();
Stack<TreeNode> stack2 = new Stack<TreeNode>();
stack1.push(root.left);stack2.push(root.right);
boolean flag = true;
while(!stack1.empty() && !stack2.empty()){
TreeNode root1 = stack1.pop();
TreeNode root2 = stack2.pop();
if( root1 != null && root2 != null){
if(root1.val != root2.val){flag = false;break;}
else{
stack1.push(root1.right);
stack1.push(root1.left);
stack2.push(root2.left);
stack2.push(root2.right);
}
}else if(root1 == null && root2 == null) continue;
else{flag = false; break;}
}
if(flag){
if(!stack1.empty() || !stack2.empty()) flag = false;
}
return flag;
}
}
本文介绍了一种判断二叉树是否对称的方法,通过递归和非递归两种方式实现了算法,并提供了详细的代码示例。对于递归方法,通过对左右子树进行对比来判断对称性;对于非递归方法,则利用两个栈来辅助实现。
249

被折叠的 条评论
为什么被折叠?



