101. Symmetric Tree
https://leetcode.com/problems/symmetric-tree/
Python
DFS
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return False
def check(left, right):
if not left or not right:
if not left and not right:
return True
return False
if left.val != right.val:
return False
return check(left.left, right.right) and \
check(left.right, right.left)
return check(root.left, root.right)
Go
DFS
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSymmetric(root *TreeNode) bool {
if root == nil {
return false
}
return check(root.Left, root.Right)
}
func check(left *TreeNode, right *TreeNode) bool {
if left == nil && right == nil {
return true
}
if left == nil || right == nil {
return false
}
if left.Val != right.Val {
return false
}
return check(left.Right, right.Left) && check(left.Left, right.Right)
}