0%

leetCode-101:Symmetric Tree

问题描述

给定一颗二叉树,要求判断二叉树是否是对称的(以根节点的垂直线进行划分)。题目链接:**点我**

样例输入输出

输入:[1,2,2]

输出:true

解释:树结构如下

1

/ \

2 2

输入:[1,2,3]

输出:false

解释:树结构如下

1

/ \

2 3

问题解法

从根节点拆分成两颗树,对于两颗树而言,要对称,则第一颗树的左节点需要对应第二颗树的右节点,第一颗树的右节点需要对应第二颗树的左节点。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* 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)
{
if (root == null)
{
return true;
}

return isSymmetric(root.left, root.right);
}

private boolean isSymmetric(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 isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
}
}