NOTE
Symmetric Tree
LeetCode notes on checking whether a binary tree is mirror-symmetric.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given a binary tree, check whether it is mirror-symmetric.
2. Approach
- Approach 1
- Preorder traversal
- Determine whether the root’s left and right subtrees mirror each other
3. Implementation
3.1. Preorder Traversal
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSymmetric(root *TreeNode) bool {
if root == nil {
return true
}
return isSymmetricDFS(root.Left, root.Right)
}
func isSymmetricDFS(left *TreeNode, right *TreeNode) bool {
if left == nil && right == nil {
return true
}
if left == nil || right == nil {
return false
}
return left.Val == right.Val && isSymmetricDFS(left.Left, right.Right) && isSymmetricDFS(left.Right, right.Left)
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub