剑指 Offer 28. 对称的二叉树【递归】

题目描述

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

1

/ \

2 2

/ \ / \

3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

1

/ \

2 2

\ \

3 3

示例 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution28 {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return Symmetric(root.left, root.right);
}

public boolean Symmetric(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
if (left.val != right.val) {
return true;
}
return Symmetric(left.right, right.left) && Symmetric(left.left, right.right);

}
}

复杂度分析

时间复杂度:O(n)

空间复杂度:O(n) //递归调用栈使用。

资源

  1. https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/
  2. 《剑指offer》

剑指 Offer 28. 对称的二叉树【递归】

http://example.com/2021/04/19/28-对称的二叉树/

Author

John Doe

Posted on

2021-04-19

Updated on

2021-06-08

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.