题目:101. 对称二叉树
给你一个二叉树的根节点
root
, 检查它是否轴对称。
解题思路
可以理解为遍历对比,最简单的方法就是递归。
解题过程
递归:左右子树分开遍历,左子树遵循根、左、右的顺序,右子树循序根、右、左,将结果进行对比。
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void leftTravel(TreeNode root, List<Integer> res) {
if (root == null) {
res.add(null);
return;
}
res.add(root.val);
leftTravel(root.left, res);
leftTravel(root.right, res);
}
public void rightTravel(TreeNode root, List<Integer> res) {
if (root == null) {
res.add(null);
return;
}
res.add(root.val);
rightTravel(root.right, res);
rightTravel(root.left, res);
}
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
if (root.left == null && root.right == null) {
return true;
}
// 左子树 根 左 右
TreeNode left = root.left;
List<Integer> resL = new ArrayList();
leftTravel(left, resL);
// 右子树 根 右 左
TreeNode right = root.right;
List<Integer> resR = new ArrayList();
rightTravel(right, resR);
// 对比 是否一致
return resL.equals(resR);
}
}
这个还可以简化,直接递归对比结果,代码如下
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean compare(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
return left.val == right.val && compare(left.left, right.right) &&
compare(left.right, right.left);
}
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return compare(root.left, root.right);
}
}