代码随想录算法训练营:16/60

一、LeetCode题目

1.LeetCode513:找树左下角的值 

题目链接:513. 找树左下角的值 - 力扣(LeetCode)

题目解析

       毫无疑问,个人认为层序遍历是最好的方法,好理解,好写;不过这里贴出了学习了用回溯搜索去写,其实就可以理解成,按照指定顺序遍历树,然后在中间满足一定条件更新变量。相当于高级的for循环(bushi),同时也优化了一个比较极致的递归版本,改变了递归条件和递归顺序。

 回溯c++代码如下:

 
  1. /**

  2. * Definition for a binary tree node.

  3. * struct TreeNode {

  4. * int val;

  5. * TreeNode *left;

  6. * TreeNode *right;

  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}

  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),

  10. * right(right) {}

  11. * };

  12. */

  13. class Solution {

  14. public:

  15. // 设定搜索是更新的临界目标

  16. int max_depth = INT_MIN;

  17. int target = 0;

  18. // 设定深度搜索函数(其实是回溯函数)

  19. void dfs(TreeNode* root, int depth) {

  20. if (!root)

  21. return;

  22. // 需要的条件:左节点,深度更大。注意!只有满足条件才会更新,要不一直在遍历回溯

  23. if (!root->left && !root->right && max_depth < depth) {

  24. max_depth = depth;

  25. target = root->val;

  26. // 注意不要return,因为要一直更新遍历

  27. }

  28. // 左子树检查

  29. if (root->left) {

  30. dfs(root->left, depth + 1);

  31. }

  32. // 右子树检查

  33. if (root->right) {

  34. dfs(root->right, depth + 1);

  35. }

  36. return;

  37. }

  38. int findBottomLeftValue(TreeNode* root) {

  39. dfs(root, 0);

  40. return target;

  41. }

  42. };

回溯加强版c++代码:

 
  1. class Solution {

  2. public:

  3. int findBottomLeftValue(TreeNode* root) {

  4. int bottomLeftValue = 0;

  5. int maxDepth = -1;

  6. dfs(root, 0, maxDepth, bottomLeftValue);

  7. return bottomLeftValue;

  8. }

  9. void dfs(TreeNode* node, int depth, int& maxDepth, int& bottomLeftValue) {

  10. if (!node) return;

  11. // 如果当前深度比已知最大深度大,或者当前节点是左节点,更新最大深度和左下角值

  12. if (depth > maxDepth || (depth == maxDepth && node->left)) {

  13. maxDepth = depth;

  14. bottomLeftValue = node->val;

  15. }

  16. // 先遍历右子树,这样左子树的节点会在相同深度下覆盖右子树的节点

  17. if (node->right) dfs(node->right, depth + 1, maxDepth, bottomLeftValue);

  18. if (node->left) dfs(node->left, depth + 1, maxDepth, bottomLeftValue);

  19. }

  20. };

 层序遍历c++代码:

 
  1. /**

  2. * Definition for a binary tree node.

  3. * struct TreeNode {

  4. * int val;

  5. * TreeNode *left;

  6. * TreeNode *right;

  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}

  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),

  10. * right(right) {}

  11. * };

  12. */

  13. class Solution {

  14. public:

  15. queue<TreeNode*> que;

  16. vector<vector<int>> result;

  17. int findBottomLeftValue(TreeNode* root) {

  18. que.push(root);

  19. int size = que.size();

  20. while (!que.empty())

  21. {

  22. vector<int> cur_vec;

  23. while (size--)

  24. {

  25. TreeNode* cur_node = que.front();

  26. que.pop();

  27. cur_vec.push_back(cur_node->val);

  28. if (cur_node->left)

  29. que.push(cur_node->left);

  30. if (cur_node->right)

  31. que.push(cur_node->right);

  32. }

  33. result.push_back(cur_vec);

  34. size = que.size();

  35. }

  36. return result.back()[0];

  37. }

  38. };

 2.Leetcode112:路径总和 

题目链接:112. 路径总和 - 力扣(LeetCode)

题目解析

       利用回溯的思想,在遇到叶子节点且满足总和条件的前提下,返回为真。左右子树都检索,最后取一个或,因为返回只要求返回bool只检查又或者没有符合条件路径。

 C++代码如下: 

 
  1. /**

  2. * Definition for a binary tree node.

  3. * struct TreeNode {

  4. * int val;

  5. * TreeNode *left;

  6. * TreeNode *right;

  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}

  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),

  10. * right(right) {}

  11. * };

  12. */

  13. class Solution {

  14. public:

  15. // 回溯搜索路径

  16. bool backtracking(TreeNode* root, int targetSum) {

  17. if (!root)

  18. return false;

  19. if (targetSum == root->val && !root->right && !root->left)

  20. return true;

  21. // backtracking(root->left,targetSum-root->val);

  22. // backtracking(root->right,targetSum - root->val);

  23. return backtracking(root->left, targetSum - root->val) ||

  24. backtracking(root->right, targetSum - root->val);

  25. }

  26. bool hasPathSum(TreeNode* root, int targetSum) {

  27. return backtracking(root, targetSum);

  28. }

  29. };

注意点:这里采用的是值传入,所以没有用显式的回溯过程,那么检验的条件也应该是targetSum == root->val,而不是等于0.

3.Leetcode106:从中序与后序遍历序列构造二叉树

题目链接:106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)

题目解析

       大致的思路是:根据后序遍历的结果锁定根节点(末尾),然后用这个值去中序红寻找并切分,这时候问题就会转移到如何根据剩下的这些条件开启下一轮的切分们也就是递归。利用合理的区间构建好左右中序数组之后,可以利用他们的相同长度去切分后序数组,这样就可以得到下一轮的数组。那么根据这个过程,对应的中止条件就是:数组无法切分,即数组为空为止。

C++代码如下:

 
  1. /**

  2. * Definition for a binary tree node.

  3. * struct TreeNode {

  4. * int val;

  5. * TreeNode *left;

  6. * TreeNode *right;

  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}

  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),

  10. * right(right) {}

  11. * };

  12. */

  13. class Solution {

  14. public:

  15. TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {

  16. // 确定中止条件

  17. if (!inorder.size() && !postorder.size())

  18. return nullptr;

  19. // 取后序数组的最后一个分割中序数组

  20. int root_num = postorder.back();

  21. int root_post = 0;

  22. for (int i = 0; i < inorder.size(); ++i) {

  23. if (inorder[i] == root_num) {

  24. root_post = i;

  25. break;

  26. }

  27. }

  28. // 创造根节点

  29. TreeNode* root = new TreeNode(root_num);

  30. // 分割为左数组和右数组

  31. vector<int> inorder_left =

  32. vector<int>(inorder.begin(), inorder.begin() + root_post);

  33. vector<int> inorder_right =

  34. vector<int>(inorder.begin() + root_post + 1, inorder.end());

  35. // 根据后序和中序遍历大小是一样的

  36. vector<int> postorder_left = vector<int>(

  37. postorder.begin(), postorder.begin() + inorder_left.size());

  38. vector<int> postorder_right = vector<int>(

  39. postorder.begin() + inorder_left.size(),

  40. postorder.begin() + inorder_left.size() + inorder_right.size());

  41. // 一层逻辑已经结束,写递归逻辑

  42. root->left = buildTree(inorder_left, postorder_left);

  43. root->right = buildTree(inorder_right, postorder_right);

  44. return root;

  45. }

  46. };

4.Leetcode105:从前序与中序遍历序列构造二叉树

题目链接:105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)

题目解析

       和后序的思路基本上是一致的,最关键的就是怎么合理的处理范围,不要超出范围或者范围混乱。

C++代码如下:

 
  1. /**

  2. * Definition for a binary tree node.

  3. * struct TreeNode {

  4. * int val;

  5. * TreeNode *left;

  6. * TreeNode *right;

  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}

  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),

  10. * right(right) {}

  11. * };

  12. */

  13. class Solution {

  14. public:

  15. TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {

  16. if (!preorder.size() && !inorder.size())

  17. return nullptr;

  18. // 获取前序数组的第一个元素

  19. int val = preorder.front();

  20. preorder.erase(preorder.begin());

  21. // 创建新节点

  22. TreeNode* root = new TreeNode(val);

  23. int pos = 0;

  24. // 在中序数组中寻找位置

  25. for (int i = 0; i < inorder.size(); ++i) {

  26. if (inorder[i] == val) {

  27. pos = i;

  28. }

  29. }

  30. // 根据获取元素分割中序数组

  31. vector<int> inorder_left =

  32. vector<int>(inorder.begin(), inorder.begin() + pos);

  33. vector<int> inorder_right =

  34. vector<int>(inorder.begin() + pos + 1, inorder.end());

  35. // 切分前序数组

  36. vector<int> preorder_left = vector<int>(

  37. preorder.begin(), preorder.begin() + inorder_left.size());

  38. vector<int> preorder_right =

  39. vector<int>(preorder.begin() + inorder_left.size(), preorder.end());

  40. root->left = buildTree(preorder_left, inorder_left);

  41. root->right = buildTree(preorder_right, inorder_right);

  42. return root;

  43. }

  44. };

注意点1:中止条件检查一个就够了,因为题目给出的遍历是合法的,所以两个数组的长度也一定一样。

注意点2:切分的时候注意迭代器写法是左闭右开,而且中止迭代器是在下一位;还有就是跨过切分点(根节点),选取区间不是连续的。

 

总结


补打卡第16天,坚持!!!

  • 23
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
代码随想录算法训练营是一个优质的学习和讨论平台,提供了丰富的算法训练内容和讨论交流机会。在训练营中,学员们可以通过观看视频讲解来学习算法知识,并根据讲解内容进行刷练习。此外,训练营还提供了刷建议,例如先看视频、了解自己所使用的编程语言、使用日志等方法来提高刷效果和语言掌握程度。 训练营中的讨论内容非常丰富,涵盖了各种算法知识点和解方法。例如,在第14天的训练营中,讲解了二叉树的理论基础、递归遍历、迭代遍历和统一遍历的内容。此外,在讨论中还分享了相关的博客文章和配图,帮助学员更好地理解和掌握二叉树的遍历方法。 训练营还提供了每日的讨论知识点,例如在第15天的讨论中,介绍了层序遍历的方法和使用队列来模拟一层一层遍历的效果。在第16天的讨论中,重点讨论了如何进行调试(debug)的方法,认为掌握调试技巧可以帮助学员更好地解决问和写出正确的算法代码。 总之,代码随想录算法训练营是一个提供优质学习和讨论环境的平台,可以帮助学员系统地学习算法知识,并提供了丰富的讨论内容和刷建议来提高算法编程能力。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [代码随想录算法训练营每日精华](https://blog.csdn.net/weixin_38556197/article/details/128462133)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值