应用题-二叉树专题-对称二叉树

管理员
[对称二叉树](https://leetcode.cn/problems/symmetric-tree/description/) ## 题目描述 给你一个二叉树的根节点 root,检查它是否轴对称(即是否关于根节点中心对称)。 **示例** ```text 输入:root = [1,2,2,3,4,4,3] 输出:true 1 / \ 2 2 / \ / \ 3 4 4 3 ``` ```text 输入:root = [1,2,2,null,3,null,3] 输出:false 1 / \ 2 2 \ \ 3 3 ``` **约束条件** 1. 树中节点数目范围:[1, 1000] 2. -100 <= Node.val <= 100 ## 解题思路 ```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: Optional[TreeNode]) -> bool: # 是否是对称二叉树, 即判断左子树和右子树是否是对称的 # 记,左右两颗子树为A和B, # 判断A树上所有节点,对应B树上所有节点, 所有对应节点都相同, 则是对称二叉树 # 如何去对应 即A树按照"根左右", B树按照"根右左",节点位置即可对应 def isSymmetric_( a, b ): if not a and b: return False if not b and a: return False if not a and not b: return True if a.val != b.val: return False # 允许向下继续对比 st1 = isSymmetric_( a.left, b.right ) st2 = isSymmetric_( a.right, b.left ) return st1 and st2 return isSymmetric_( root.left, root.right ) ``` **时间复杂度: `O(n)`** **空间复杂度: `O(h)`** n = 节点总数 h = 树的高度 ( 最坏情况`O(n)` 最好情况`O(log n)` )
评论 0

发表评论 取消回复

Shift+Enter 换行  ·  Enter 发送
还没有评论,来发表第一条吧