·leetcode - 101 - 对称二叉树
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false
提示:
- 树中节点数目在范围
[1, 1000]
内 -100 <= Node.val <= 100
·解题思路
刚刚学了广义遍历,所以想是否可以创建一个队列,将每一层的结点压入队列中,再判断是否是对称。这里有个小技巧是,将需要判断是否是相等的两个结点放到一处。根据前后弹出的两个结点判断是否相等,从而判断是否是对称树。
·代码实现
Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;class Solution {public boolean isSymmetric(TreeNode root) {return check(root , root);}public boolean check(TreeNode root1, TreeNode root2) {Queue<TreeNode> queue = new LinkedList<TreeNode>();queue.offer(root1);queue.offer(root2);while(!queue.isEmpty() ) {TreeNode l = queue.poll(), r = queue.poll();if(l == null && r == null) continue;if(l == null || r == null || l.val != r.val) return false;queue.offer(l.left);queue.offer(r.right);queue.offer(l.right);queue.offer(r.left);}return true;}public class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) { val = x; }TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
}