101. 对称二叉树(树)
程序员文章站
2024-01-11 17:17:22
...
方法一:递归
一棵树是对称的,当它的左子树和右子树是镜像时,满足条件;所以用递归很好解决
/**
* 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 symmetric(root.left,root.right);
}
public boolean symmetric(TreeNode t1,TreeNode t2){
if(t1 == null && t2 == null) return true;
if(t1 == null || t2 == null) return false;
if(t1.val != t2.val) return false;
//关键
return symmetric(t1.left,t2.right) && symmetric(t2.left,t1.right);
}
}
方法二:迭代
使用队列;限制左右子节点的入队顺序
(
queue.add(t1.left);
queue.add(t2.right);
queue.add(t1.right);
queue.add(t2.left);
)
使对称二叉树入队后相邻两个节点的值始终相等,为了操作的一致性将根节点入队两次;
/**
* 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.remove();
TreeNode t2 = queue.remove();
if(t1 == null && t2 == null) continue;//return true;
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;
}
}
下一篇: 力扣101 对称二叉树