zoukankan      html  css  js  c++  java
  • LeetCode题解之Convert BST to Greater Tree

    1、题目描述

    2、问题分析

    使用一个vector将所有节点的值以升序排列。然后比较,求和,加上。

    3、代码

     1 TreeNode* convertBST(TreeNode* root) {
     2       if (root == NULL)
     3           return NULL;
     4         
     5         vector<int> v;
     6         inorder(root,v);
     7         increaseVal(root, v);
     8         
     9         return root;
    10         
    11     }
    12     
    13     void increaseVal(TreeNode *root, vector<int> &v)
    14     {
    15         if(root == NULL)
    16             return ;
    17         int sum = 0;
    18         auto it = find(v.begin(), v.end(), root->val);
    19         if (it != v.end() - 1) {
    20             sum = accumulate(it + 1, v.end(), 0);
    21             root->val = root->val + sum;
    22         }
    23         
    24         increaseVal(root->left, v);
    25         increaseVal(root->right, v);
    26     }
    27     
    28     void inorder(TreeNode *root, vector<int> &v)
    29     {
    30         if (root == NULL)
    31             return ;
    32         inorder(root->left, v);
    33         v.push_back(root->val);
    34         inorder(root->right,v);
    35     }
  • 相关阅读:
    centos7安装kde桌面
    centos7安装NVIDIA驱动
    15日报
    11日报
    14日报
    奖励加分
    课程建议
    13日报
    12日报
    每日总结1213
  • 原文地址:https://www.cnblogs.com/wangxiaoyong/p/10433107.html
Copyright © 2011-2022 走看看