From 99d28fcc002dc5bb40952f01d3c975ec46b867b5 Mon Sep 17 00:00:00 2001 From: baici1 <249337001@qq.com> Date: Fri, 15 Oct 2021 16:21:58 +0800 Subject: [PATCH] =?UTF-8?q?337.=E6=89=93=E5=AE=B6=E5=8A=AB=E8=88=8D?= =?UTF-8?q?=E2=85=A2=20=E5=A2=9E=E5=8A=A0go=E7=9A=84=E8=A7=A3=E6=B3=95=20?= =?UTF-8?q?=E6=A0=91=E5=BD=A2DP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...345\256\266\345\212\253\350\210\215III.md" | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git "a/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" "b/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" index 949137c39b..204c381527 100644 --- "a/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" +++ "b/problems/0337.\346\211\223\345\256\266\345\212\253\350\210\215III.md" @@ -368,6 +368,48 @@ class Solution: return (val1, val2) ``` +Go: + +树形DP + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func rob(root *TreeNode) int { + return max(robTree(root)) +} +func robTree(root *TreeNode)(int,int){ + if root==nil{ + return 0,0 + } + //获取左节点的偷的值与不偷的值 + left0,left1:=robTree(root.Left) + //获取右节点的偷的值与不偷的值 + right0,right1:=robTree(root.Right) + //偷 + val1:=root.Val + val1+=left1+right1 + //不偷 + val2:=0 + val2+=max(left0,left1)+max(right0,right1) + return val1,val2 +} +func max(a,b int)int{ + if a>b{ + return a + } + return b +} +``` + + + JavaScript: > 动态规划