Update 0101

This commit is contained in:
YDZ
2021-04-19 10:21:24 +08:00
parent 5fbca5f096
commit 8ee289c17c
22 changed files with 570 additions and 471 deletions

View File

@ -16,19 +16,51 @@ type TreeNode = structures.TreeNode
* }
*/
// 解法一 dfs
func isSymmetric(root *TreeNode) bool {
var dfs func(rootLeft, rootRight *TreeNode) bool
dfs = func(rootLeft, rootRight *TreeNode) bool {
if rootLeft == nil && rootRight == nil {
return true
}
if rootLeft == nil || rootRight == nil {
return false
}
if rootLeft.Val != rootRight.Val {
return false
}
return dfs(rootLeft.Left, rootRight.Right) && dfs(rootLeft.Right, rootRight.Left)
}
return root == nil || dfs(root.Left, root.Right)
}
func dfs(rootLeft, rootRight *TreeNode) bool {
if rootLeft == nil && rootRight == nil {
return true
}
if rootLeft == nil || rootRight == nil {
return false
}
if rootLeft.Val != rootRight.Val {
return false
}
return dfs(rootLeft.Left, rootRight.Right) && dfs(rootLeft.Right, rootRight.Left)
}
// 解法二
func isSymmetric1(root *TreeNode) bool {
if root == nil {
return true
}
return isSameTree(invertTree(root.Left), root.Right)
}
func isSameTree(p *TreeNode, q *TreeNode) bool {
if p == nil && q == nil {
return true
} else if p != nil && q != nil {
if p.Val != q.Val {
return false
}
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
} else {
return false
}
}
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
invertTree(root.Left)
invertTree(root.Right)
root.Left, root.Right = root.Right, root.Left
return root
}