From ecf5ff1dc832b028e377d4afed3bfbf5f6317573 Mon Sep 17 00:00:00 2001 From: X-shuffle <53906918+X-shuffle@users.noreply.github.com> Date: Sat, 12 Jun 2021 14:24:04 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=EF=BC=9A=E4=BB=A5=E4=B8=BA=E4=BD=BF=E7=94=A8=E4=BA=86?= =?UTF-8?q?=E9=80=92=E5=BD=92=EF=BC=8C=E5=85=B6=E5=AE=9E=E8=BF=98=E9=9A=90?= =?UTF-8?q?=E8=97=8F=E7=9D=80=E5=9B=9E=E6=BA=AF=20go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 二叉树:以为使用了递归,其实还隐藏着回溯 go版本 --- problems/二叉树中递归带着回溯.md | 104 +++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/problems/二叉树中递归带着回溯.md b/problems/二叉树中递归带着回溯.md index aede1831..8014d6e1 100644 --- a/problems/二叉树中递归带着回溯.md +++ b/problems/二叉树中递归带着回溯.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]//回溯 + } +} +``` + +