精華區beta Marginalman 關於我們 聯絡資訊
※ 引述《oin1104 (是oin的說)》之銘言: : 題目 : : 把binary search tree : 變成Greater Sum Tree : 反正就是在二元搜尋樹 : 對每個數字 把比他大的東西加起來 思路: 1.找出二元搜尋樹遞迴的關係然後dfs即可 java code --------------------------------------------------- class Solution { public TreeNode bstToGst(TreeNode root) { dfs(root, 0); return root; } private int dfs(TreeNode root, int sum) { if (root == null) { return sum; } int r = dfs(root.right, sum); root.val += r; int l = dfs(root.left, root.val); return Math.max(l, root.val); } } ---------------------------------------------------- -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1719287682.A.CC2.html ※ 編輯: Rushia (122.100.73.13 臺灣), 06/25/2024 11:55:39
oin1104: 大師 06/25 11:55