添加 二叉树:以为使用了递归,其实还隐藏着回溯 go版本

添加 二叉树:以为使用了递归,其实还隐藏着回溯 go版本
This commit is contained in:
X-shuffle
2021-06-12 14:24:04 +08:00
committed by GitHub
parent 2c24d81861
commit ecf5ff1dc8

View File

@ -336,6 +336,110 @@ class Solution:
``` ```
Go 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<len(*path);i++{
pathStr=pathStr+"->"+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]//回溯
}
}
```