From e89796c624a8ed941fc28002bec0595992ceb3ed Mon Sep 17 00:00:00 2001 From: X-shuffle <53906918+X-shuffle@users.noreply.github.com> Date: Sat, 12 Jun 2021 21:55:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20513.=E6=89=BE=E6=A0=91?= =?UTF-8?q?=E5=B7=A6=E4=B8=8B=E8=A7=92=E7=9A=84=E5=80=BC=20go=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 513.找树左下角的值 go版本 --- problems/0513.找树左下角的值.md | 74 ++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 97464e3d..e252ccd3 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -298,6 +298,80 @@ class Solution: ``` Go: +> 递归法 + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + var maxDeep int // 全局变量 深度 + var value int //全局变量 最终值 +func findBottomLeftValue(root *TreeNode) int { + if root.Left==nil&&root.Right==nil{//需要提前判断一下(不要这个if的话提交结果会出错,但执行代码不会。防止这种情况出现,故先判断是否只有一个节点) + return root.Val + } + findLeftValue (root,maxDeep) + return value +} +func findLeftValue (root *TreeNode,deep int){ + //最左边的值在左边 + if root.Left==nil&&root.Right==nil{ + if deep>maxDeep{ + value=root.Val + maxDeep=deep + } + } + //递归 + if root.Left!=nil{ + deep++ + findLeftValue(root.Left,deep) + deep--//回溯 + } + if root.Right!=nil{ + deep++ + findLeftValue(root.Right,deep) + deep--//回溯 + } +} +``` + +> 迭代法 + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func findBottomLeftValue(root *TreeNode) int { + queue:=list.New() + var gradation int + queue.PushBack(root) + for queue.Len()>0{ + length:=queue.Len() + for i:=0;i