给定一个二叉树,检查它是否是镜像对称的。 例如,二叉树 `[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 **进阶:** 你可以运用递归和迭代两种方法解决这个问题吗? 附赠leetcode地址:[leetcode](https://leetcode-cn.com/problems/symmetric-tree/solution/javascriptdui-cheng-er-cha-shu-by-user7746o/)
Activity
plane-hjh commentedon May 27, 2020
递归
比较二叉树的 前序遍历 和 对称前序遍历 来判断是不是对称的。
前序遍历:根-左-右
对称前序遍历:根-右-左
7777sea commentedon May 27, 2020
fanefanes commentedon May 27, 2020
递归
迭代
plane-hjh commentedon May 27, 2020
@fanefanes 这个迭代学到了,感谢~
jasonting5 commentedon May 27, 2020
sisterAn commentedon May 27, 2020
解答:
一棵二叉树对称,则需要满足:根的左右子树是镜像对称的
也就是说,每棵树的左子树都和另外一颗树的右子树镜像对称,左子树的根节点值与右子树的根节点值相等
所以,我们需要比较:
边界条件:
null时,返回truenull时,返回false解法一:递归
复杂度分析:
解法二:迭代
利用栈来记录比较的过程,实际上,递归就使用了调用栈,所以这里我们可以使用栈来模拟递归的过程
left、右子树的right、左子树的right、右子树的left依次入栈依次循环出栈入栈,直到栈为空
复杂度分析:
leetcode
luweiCN commentedon May 27, 2020
AnranS commentedon Nov 20, 2020
xiaowuge007 commentedon Apr 27, 2021