牛客题霸-判读二叉树是否对称-Java题解
判断二叉树是否对称
http://www.nowcoder.com/questionTerminal/1b0b7f371eae4204bc4a7570c84c2de1
题目:https://www.nowcoder.com/practice/1b0b7f371eae4204bc4a7570c84c2de1
题解:这道题需要注意的地方就是对称的意思的理解,当root的左右孩子left和right的数值相等,同时left.left和right.right以及left.right和right.left分别对应对称时,root是对称的。这道题可以使用递归和迭代(使用队列)来做,具体可参见代码
java代码实现:
import java.util.*; public class Solution { /** * * @param root TreeNode类 * @return bool布尔型 */ public boolean isSymmetric (TreeNode root) { if(root == null) return true; return check(root.left, root.right); } //递归 public boolean check(TreeNode left, TreeNode right){ if(left == null && right == null) return true; if(left == null || right == null) return false; return left.val == right.val && check(left.left, right.right) && check(left.right, right.left); } //迭代 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; } }