Re: [閒聊] 每日leetcode

看板Marginalman作者 (6B)時間1年前 (2024/10/23 15:58), 編輯推噓2(200)
留言2則, 2人參與, 1年前最新討論串1030/1548 (看更多)
2641. 我的做法 前面跟昨天一樣 先把lv sum算出來 然後每個node去算他的child /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int lv_sum[100001]; TreeNode* replaceValueInTree(TreeNode* root) { memset(lv_sum, 0, sizeof(lv_sum)); root->val = 0; set_lv_sum(root, 0); set_child(root, 1); return root; } void set_lv_sum(TreeNode* t, int lv){ if(t == nullptr) return; lv_sum[lv] += t->val; if(t->left) set_lv_sum(t->left, lv+1); if(t->right) set_lv_sum(t->right, lv+1); } void set_child(TreeNode* t, int child_lv){ if(t == nullptr) return; int child_sum = 0; if(t->left) child_sum += t->left->val; if(t->right) child_sum += t->right->val; if(t->left) { t->left->val = lv_sum[child_lv] - child_sum; set_child(t->left, child_lv + 1); } if(t->right){ t->right->val = lv_sum[child_lv] - child_sum; set_child(t->right, child_lv + 1); } } }; 做了bfs 好像比dfs慢== 而且空間也耗滿蠻多的 -- 很姆的咪 姆之咪 http://i.imgur.com/5sw7QOj.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.231.137.218 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1729670290.A.013.html

10/23 16:02, 1年前 , 1F
大師
10/23 16:02, 1F

10/23 16:13, 1年前 , 2F
大師
10/23 16:13, 2F
文章代碼(AID): #1d6AoI0J (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1d6AoI0J (Marginalman)