目录
[101. 对称二叉树](#101. 对称二叉树)
莫道浮云终蔽日
总有雾散云开时
昨日之深渊
今日之浅谈
------ 24.10.20
101. 对称二叉树
给你一个二叉树的根节点
root
, 检查它是否轴对称。示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false
思路
若要判断一个二叉树是否对称,只需要判断从根节点的下一层开始是否轴对称,判断轴对称只需要判断左孩子的左孩子节点是否与右孩子的右孩子节点相等,遍历到叶子节点,逐层进行判断,是否从根节点开始左孩子的左孩子...的左孩子与右孩子的右孩子......的右孩子节点完全相等
代码
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 isSymmetric(TreeNode root) {
return check(root.left,root.right);
}
private boolean check(TreeNode left,TreeNode right){
if(left == null && right == null){
return true;
}
if(left == null || right == null){
return false;
}
if (left.val != right.val){
return false;
}
return check(left.left,right.right) && check(left.right,right.left);
}
}
Java代码及测试用例
java
public class LeetCode101SymmetryBinaryTree {
public boolean isSymmetric(TreeNode root) {
return check(root.left,root.right);
}
private boolean check(TreeNode left,TreeNode right){
if(left == null && right == null){
return true;
}
if(left == null || right == null){
return false;
}
if (left.value != right.value){
return false;
}
return check(left.left,right.right) && check(left.right,right.left);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(
1,
new TreeNode(2,new TreeNode(3),new TreeNode(4)),
new TreeNode(2,new TreeNode(4),new TreeNode(3))
);
LeetCode101SymmetryBinaryTree res = new LeetCode101SymmetryBinaryTree();
System.out.println(res.isSymmetric(root));
TreeNode root1 = new TreeNode(
11,
new TreeNode(7,
new TreeNode(5,
new TreeNode(3),
new TreeNode(6)),
new TreeNode(9,
new TreeNode(2),
new TreeNode(8))
),
new TreeNode(11,
new TreeNode(4,
new TreeNode(9),
new TreeNode(28)),
new TreeNode(5)
)
);
System.out.println(res.isSymmetric(root1));
}
}