leetcode 101. 对称二叉树

题解

递归,判断左子树的左边和右子树的右边,以及左子树的右边和右子树的左边是否相同

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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 isLRSymmetric(root.Left, root.Right)
}

func isLRSymmetric(left, right *TreeNode) bool {
if left == nil && right != nil {
return false
}
if left != nil && right == nil {
return false
}
if left == nil && right == nil {
return true
}
if left.Val != right.Val {
return false
}
return isLRSymmetric(left.Left, right.Right) && isLRSymmetric(left.Right, right.Left)
}