From c03d5310a736f16accb2bf2e294743ac24e7d913 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Mon, 5 Dec 2022 19:13:43 +0800 Subject: [PATCH] =?UTF-8?q?update=200538.=E6=8A=8A=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E8=BD=AC=E6=8D=A2=E4=B8=BA=E7=B4=AF?= =?UTF-8?q?=E5=8A=A0=E6=A0=91=EF=BC=9A=E6=9B=BF=E6=8D=A2=20go=20=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...38.把二叉搜索树转换为累加树.md | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/problems/0538.把二叉搜索树转换为累加树.md b/problems/0538.把二叉搜索树转换为累加树.md index 823771b1..9940e604 100644 --- a/problems/0538.把二叉搜索树转换为累加树.md +++ b/problems/0538.把二叉搜索树转换为累加树.md @@ -45,11 +45,11 @@ # 思路 -一看到累加树,相信很多小伙伴都会疑惑:如何累加?遇到一个节点,然后在遍历其他节点累加?怎么一想这么麻烦呢。 +一看到累加树,相信很多小伙伴都会疑惑:如何累加?遇到一个节点,然后再遍历其他节点累加?怎么一想这么麻烦呢。 然后再发现这是一棵二叉搜索树,二叉搜索树啊,这是有序的啊。 -那么有序的元素如果求累加呢? +那么有序的元素如何求累加呢? **其实这就是一棵树,大家可能看起来有点别扭,换一个角度来看,这就是一个有序数组[2, 5, 13],求从后到前的累加数组,也就是[20, 18, 13],是不是感觉这就简单了。** @@ -233,23 +233,23 @@ class Solution: ## Go 弄一个sum暂存其和值 - ```go - //右中左 -func bstToGst(root *TreeNode) *TreeNode { - var sum int - RightMLeft(root,&sum) - return root -} -func RightMLeft(root *TreeNode,sum *int) *TreeNode { - if root==nil{return nil}//终止条件,遇到空节点就返回 - RightMLeft(root.Right,sum)//先遍历右边 - temp:=*sum//暂存总和值 - *sum+=root.Val//将总和值变更 - root.Val+=temp//更新节点值 - RightMLeft(root.Left,sum)//遍历左节点 +var pre int +func convertBST(root *TreeNode) *TreeNode { + pre = 0 + traversal(root) return root } + +func traversal(cur *TreeNode) { + if cur == nil { + return + } + traversal(cur.Right) + cur.Val += pre + pre = cur.Val + traversal(cur.Left) +} ``` ## JavaScript