原题
https://leetcode.cn/problems/symmetric-tree/description/
思路
递归
复杂度
时间:O(n)
空间:O(n)
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:
def isMirror(node1, node2):
if not node1 and not node2:
return True
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
return isMirror(node1.left, node2.right) and isMirror(node1.right, node2.left)
return isMirror(root.left, root.right)
Go代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSymmetric(root *TreeNode) bool {
// 匿名函数
var isMirror func(*TreeNode, *TreeNode) bool
isMirror = func(node1 *TreeNode, node2 *TreeNode) bool {
if node1 == nil && node2 == nil {
return true
}
if node1 == nil || node2 == nil {
return false
}
if node1.Val != node2.Val {
return false
}
return isMirror(node1.Left, node2.Right) && isMirror(node1.Right, node2.Left)
}
return isMirror(root.Left, root.Right)
}
742

被折叠的 条评论
为什么被折叠?



