AcWing 39. 对称的二叉树 -- JAVA 2种方式
原题链接
简单
算法1
代码
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null){
return true;
}
return isSymmetric0(root.left,root.right);
}
private boolean isSymmetric0(TreeNode p1, TreeNode p2){
if (p1 == null && p2 == null){
return true;
}
if (p1 == null || p2 == null){
return false;
}
return p1.val == p2.val && isSymmetric0(p1.left,p2.right) && isSymmetric0(p1.right,p2.left);
}
}
算法2
代码
boolean isSymmetricalDFS(TreeNode pRoot) {
if(pRoot == null) return true;
Stack<TreeNode> s = new Stack<>();
s.push(pRoot.left);
s.push(pRoot.right);
while(!s.empty()) {
TreeNode right = s.pop();//成对取出
TreeNode left = s.pop();
if(left == null && right == null) continue;
if(left == null || right == null) return false;
if(left.val != right.val) return false;
//成对插入
s.push(left.left);
s.push(right.right);
s.push(left.right);
s.push(right.left);
}
return true;
}
class Solution {
// 判断给定的二叉树是否对称
public boolean isSymmetric(TreeNode root) {
// 如果根节点为空,则认为它是对称的
if (root == null){
return true;
}
// 调用辅助函数isSymmetric0来检查左右子树是否对称
return isSymmetric0(root.left,root.right);
}
}
bfs vs dfs写得好!