
题目描述
101. 对称二叉树
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:

1 2
| 输入:root = [1,2,2,3,4,4,3] 输出:true
|
示例 2:

1 2
| 输入:root = [1,2,2,null,3,null,3] 输出:false
|
提示:
- 树中节点数目在范围
[1, 1000]
内
-100 <= Node.val <= 100
解题思路

代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public class Solution101Case1 { public static boolean isSymmetric(TreeNode root) { return check(root, root); }
public static boolean check(TreeNode p, TreeNode q) { if (p == null && q == null) { return true; } if (p == null || q == null) { return false; } return p.val == q.val && check(p.left, q.right) && check(p.right, q.left); }
public static void main(String[] args) { TreeNode node4 = new TreeNode(4); TreeNode node5 = new TreeNode(4); TreeNode node2 = new TreeNode(2, node4, null); TreeNode node3 = new TreeNode(2, null, node5); TreeNode node1 = new TreeNode(1, node2, node3); System.err.println(isSymmetric(node1)); } }
|