讨论/《零起步学算法》 - 练习:对称二叉树/
《零起步学算法》 - 练习:对称二叉树
共 1 个回复
class Solution {
    public boolean isSymmetric(TreeNode root) {
    //广度优先搜索 => 层级遍历 => bfs
    if(root == null) {
      return false;
    }
    //队列
    Deque<TreeNode> queue = new LinkedList<>();
    //根结点放入栈
    queue.offerLast(root);
    queue.offerLast(root);
    while(!queue.isEmpty()) {
        //出队列
        TreeNode head1 = queue.pollLast();
        TreeNode head2 = queue.pollLast();
        if(head1 == null && head2 == null) {
          continue;
        }
        if((head1 == null || head2 == null) || (head2.val != head1.val)) {
          return false;
        }
        queue.offerLast(head1.left);
        queue.offerLast(head2.right);

        queue.offerLast(head1.right);
        queue.offerLast(head2.left);
    }
    return true;
    }
}
1