大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.5 KiB

  1. /*
  2. :
  3. root
  4. [1,2,3,4,5]
  5. 11
  6. */
  7. #include <bits/stdc++.h>
  8. using namespace std;
  9. #define emp -1
  10. int maxSum = 0;
  11. struct Node{
  12. int value;
  13. Node* left;
  14. Node* right;
  15. };
  16. Node* createNode(){
  17. Node* root = new Node();
  18. root->left = nullptr;
  19. root->right = nullptr;
  20. return root;
  21. }
  22. void createFullBT_DFS(Node *&root, vector<int> &numbers, int len, int i) {
  23. if(i <= len) {
  24. root->value = numbers[i - 1];
  25. if(2 * i <= len && numbers[2 * i - 1] != emp) {
  26. root->left = createNode();
  27. createFullBT_DFS(root->left, numbers, len, 2 * i);
  28. }
  29. if((2 * i + 1) <= len && numbers[2 * i] != emp) {
  30. root->right = createNode();
  31. createFullBT_DFS(root->right, numbers, len, 2 * i + 1);
  32. }
  33. }
  34. }
  35. int maxGain(Node* node) {
  36. if (node == nullptr) {
  37. return 0;
  38. }
  39. // 递归计算左右子节点的最大贡献值
  40. // 只有在最大贡献值大于 0 时,才会选取对应子节点
  41. int leftGain = max(maxGain(node->left), 0);
  42. int rightGain = max(maxGain(node->right), 0);
  43. // 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
  44. int priceNewpath = node->value + leftGain + rightGain;
  45. // 更新答案
  46. maxSum = max(maxSum, priceNewpath);
  47. // 返回节点的最大贡献值
  48. return node->value + max(leftGain, rightGain);
  49. }
  50. void preOrder(Node *root) {
  51. if(root != NULL) {
  52. cout << root->value << " ";
  53. preOrder(root->left);
  54. preOrder(root->right);
  55. }
  56. }
  57. int main(){
  58. string str = "[1,2,3,4,5]";
  59. string str_update = str.substr(1, str.length()-2);
  60. char* str_input = (char*)str_update.c_str();
  61. vector<int> nums;
  62. int val = 0;
  63. while(*str_input != '\0'){
  64. if(*str_input != ','){
  65. val = val * 10 + (*str_input - '0');
  66. }
  67. else{
  68. nums.push_back(val);
  69. val = 0;
  70. }
  71. str_input++;
  72. }
  73. nums.push_back(val);
  74. Node* root = createNode();
  75. createFullBT_DFS(root, nums, nums.size(), 1);
  76. // preOrder(root);
  77. maxGain(root);
  78. cout << maxSum <<endl;
  79. return 0;
  80. }