跟着carl学算法,本系列博客仅做个人记录,建议大家都去看carl本人的博客,写的真的很好的!
代码随想录
LeetCode:101. 对称二叉树
给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
递归法,类似后序遍历,按照左右中的顺序依次比较
public boolean isSymmetric(TreeNode root) {if (root == null)return true;return compare(root.left, root.right);}private boolean compare(TreeNode left, TreeNode right) {if (left == null && right != null)return false;else if (left != null && right == null)return false;else if (left == null && right == null)return true;else if (left != null && right != null && left.val != right.val)return false;else {boolean flag1 = compare(left.left, right.right);boolean flag2 = compare(left.right, right.left);return flag1 && flag2;}}
迭代法,使用队列来实现,使用队列来成对的存放需要比较的元素
public boolean isSymmetric(TreeNode root) {if (root == null)return true;Queue<TreeNode> queue = new LinkedList<>();queue.offer(root.left);queue.offer(root.right);while (!queue.isEmpty()) {// 通过队列来成对的存放需要比较的元素TreeNode left = queue.poll();TreeNode right = queue.poll();if (left == null && right == null)continue;if (left == null || right == null || left.val != right.val)return false;queue.offer(left.left);queue.offer(right.right);queue.offer(left.right);queue.offer(right.left);}return true;}