当前位置:   article > 正文

代码随想录算法训练营第十七天|二叉树

代码随想录算法训练营第十七天|二叉树

110. 平衡二叉树

  1. class Solution {
  2. public:
  3. int height(TreeNode* root) {
  4. if (root == nullptr) return 0;
  5. int heightLeft = height(root->left);
  6. int heightRight = height(root->right);
  7. if (heightLeft == -1 || heightRight == -1 || abs(heightLeft - heightRight) > 1) {
  8. return -1;
  9. }
  10. return max(heightLeft, heightRight) + 1;
  11. }
  12. bool isBalanced(TreeNode* root) {
  13. return height(root) >= 0;
  14. }
  15. };

257. 二叉树的所有路径

  1. class Solution {
  2. public:
  3. vector<string> result;
  4. void dfs(TreeNode* root, string path) {
  5. if (root == nullptr) return;
  6. if (root->left == nullptr && root->right == nullptr) {
  7. result.push_back(path + to_string(root->val));
  8. }
  9. if (root->left) {
  10. dfs(root->left, path + to_string(root->val) + "->");
  11. }
  12. if (root->right) {
  13. dfs(root->right, path + to_string(root->val) + "->");
  14. }
  15. }
  16. vector<string> binaryTreePaths(TreeNode* root) {
  17. string path;
  18. dfs(root, path);
  19. return result;
  20. }
  21. };

404. 左叶子之和

  1. class Solution {
  2. public:
  3. int sumLeft(TreeNode* root, bool leftLeaves) {
  4. if (root == nullptr) return 0;
  5. if (root->left == nullptr && root->right == nullptr && leftLeaves) {
  6. return root->val;
  7. }
  8. if (root->left && root->right) {
  9. return sumLeft(root->left, true) + sumLeft(root->right, false);
  10. }
  11. else if (root->left) {
  12. return sumLeft(root->left, true);
  13. }
  14. else {
  15. return sumLeft(root->right, false);
  16. }
  17. }
  18. int sumOfLeftLeaves(TreeNode* root) {
  19. if (root == nullptr) return 0;
  20. return sumLeft(root, false);
  21. }
  22. };

一切尽在不言中,自己的代码量需要不断积累,欲速则不达

这个学期的学系会很累,会很忙,但是无论如何记住,不要给自己所谓的计划,尽量少玩一点,能用来学习的时间就用来学习,尽力而为即可,不要去想结果能够怎么样,但是对自己也有要求,目标这学期每门课都能拿到3.7,不要像之前那样抱着什么都无所谓的态度了,认真看待每门课与考试

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/694909
推荐阅读
相关标签
  

闽ICP备14008679号