diff --git "a/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" "b/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" index aede183191..8014d6e11c 100644 --- "a/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" +++ "b/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" @@ -336,6 +336,110 @@ class Solution: ``` Go: +100.相同的树 +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isSameTree(p *TreeNode, q *TreeNode) bool { + switch { + case p == nil && q == nil: + return true + case p == nil || q == nil: + fmt.Println(p,q) + fallthrough + case p.Val != q.Val: + return false + } + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) +} +``` + +257.二叉的所有路径 +> 递归法 + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func binaryTreePaths(root *TreeNode) []string { + var result []string + traversal(root,&result,"") + return result +} +func traversal(root *TreeNode,result *[]string,pathStr string){ + //判断是否为第一个元素 + if len(pathStr)!=0{ + pathStr=pathStr+"->"+strconv.Itoa(root.Val) + }else{ + pathStr=strconv.Itoa(root.Val) + } + //判断是否为叶子节点 + if root.Left==nil&&root.Right==nil{ + *result=append(*result,pathStr) + return + } + //左右 + if root.Left!=nil{ + traversal(root.Left,result,pathStr) + } + if root.Right!=nil{ + traversal(root.Right,result,pathStr) + } +} +``` + +> 回溯法 + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func binaryTreePaths(root *TreeNode) []string { + var result []string + var path []int + traversal(root,&result,&path) + return result +} +func traversal(root *TreeNode,result *[]string,path *[]int){ + *path=append(*path,root.Val) + //判断是否为叶子节点 + if root.Left==nil&&root.Right==nil{ + pathStr:=strconv.Itoa((*path)[0]) + for i:=1;i"+strconv.Itoa((*path)[i]) + } + *result=append(*result,pathStr) + return + } + //左右 + if root.Left!=nil{ + traversal(root.Left,result,path) + *path=(*path)[:len(*path)-1]//回溯到上一个节点(因为traversal会加下一个节点值到path中) + } + if root.Right!=nil{ + traversal(root.Right,result,path) + *path=(*path)[:len(*path)-1]//回溯 + } +} +``` + +