[抄题]:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / 2 2 / \ / 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / 2 2 \ 3 3
[暴力解法]:
时间分析:
空间分析:
[思维问题]:
不知道有什么数学规律的时候,分情况讨论:分左右两边
[一句话思路]:
- 以为要写很多right,left:只要写基本的两个点能一直嵌套递归了,这就是recursion的作用啊!
- 而且必须两点之间有关系才能递归,一个点只能往下继承
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- recursion是嵌套调用,是用函数来实现的,不是用等号。要写函数名,看来还没理解
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
true false写之前想清楚
[总结]:
recursion是嵌套调用,是用函数来实现的,不是用等号。
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[关键模板化代码]:
public boolean isSymmetricHelper(TreeNode left, TreeNode right) { //all null if (left == null && right == null) { return true; } //one null if (left == null || right == null) { return false; } //not same if (left.val != right.val) { return false; } //same return isSymmetricHelper(left.left, right.right) && isSymmetricHelper(left.right, right.left); //don‘t forget the function name }
[其他解法]:
stack能写死。
非递归就只要学pre-order in-order就行了
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { //corner case if (root == null) { return true; } return isSymmetricHelper(root.left, root.right); } public boolean isSymmetricHelper(TreeNode left, TreeNode right) { //all null if (left == null && right == null) { return true; } //one null if (left == null || right == null) { return false; } //not same if (left.val != right.val) { return false; } //same return isSymmetricHelper(left.left, right.right) && isSymmetricHelper(left.right, right.left); //don‘t forget the function name } }