对称二叉树
给你一个二叉树的根节点 root , 检查它是否轴对称。
示例1:
输入:root = [1,2,2,3,4,4,3]
输出:true
解题思路
判断一棵二叉树是否是轴对称的,可以通过递归方式进行判断。
- 1、定义一个递归函数isMirror,用于判断两个节点是否是镜像对称的。
- 2、判断当前节点的左子树和右子树是否是镜像对称的。
- 3、如果左子树和右子树都为空,返回true。
- 4、如果左子树和右子树其中一个为空,返回false。
- 5、如果左子树的值等于右子树的值,
并且左子树的左子树与右子树的右子树镜像对称,
左子树的右子树与右子树的左子树镜像对称,
则返回true,否则返回false。
Java实现
public class SymmetricTree {static class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int val) {this.val = val;}}public boolean isSymmetric(TreeNode root) {if (root == null) {return true; // 空树是对称的}return isMirror(root.left, root.right);}private boolean isMirror(TreeNode left, TreeNode right) {// 如果两个节点都为空,是对称的if (left == null && right == null) {return true;}// 如果其中一个节点为空,另一个不为空,不对称if (left == null || right == null) {return false;}// 递归比较左子树的左节点和右子树的右节点,以及左子树的右节点和右子树的左节点return (left.val == right.val) && isMirror(left.left, right.right) && isMirror(left.right, right.left);}// 测试实例public static void main(String[] args) {// 构造对称的二叉树: 1// / \// 2 2// / \ / \// 3 4 4 3TreeNode symmetricTree = new TreeNode(1);symmetricTree.left = new TreeNode(2);symmetricTree.right = new TreeNode(2);symmetricTree.left.left = new TreeNode(3);symmetricTree.left.right = new TreeNode(4);symmetricTree.right.left = new TreeNode(4);symmetricTree.right.right = new TreeNode(3);// 创建 SymmetricTreeChecker 实例SymmetricTree checker = new SymmetricTree();// 检查对称的二叉树boolean isSymmetric = checker.isSymmetric(symmetricTree);System.out.println("是否是对称二叉树: " + isSymmetric);// 构造非对称的二叉树: 1// / \// 2 2// \ \// 3 3TreeNode asymmetricTree = new TreeNode(1);asymmetricTree.left = new TreeNode(2);asymmetricTree.right = new TreeNode(2);asymmetricTree.left.right = new TreeNode(3);asymmetricTree.right.right = new TreeNode(3);// 检查非对称的二叉树boolean isAsymmetric = checker.isSymmetric(asymmetricTree);System.out.println("是否是对称二叉树: " + isAsymmetric);}
}
时间空间复杂度
- 时间复杂度:O(n),其中n是二叉树中的节点数,每个节点都需要访问一次。
- 空间复杂度:O(height),其中height是二叉树的高度,递归调用栈的深度。