Convert BST to Greater Tree

    xiaoxiao2021-03-25  105

    题目:

    Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

    Example:

    Input: The root of a Binary Search Tree like this: 5 / \ 2 13 Output: The root of a Greater Tree like this: 18 / \ 20 13

    题目意思:

    给一个二叉搜索树, 将它转化为更大的二叉树,使得节点的值为原始节点的值加上所有比它大的节点的值之和,并且使转化后的二叉树的左子树大于右子树。

    解题思路:

    设置一个数组,对二叉树进行中序遍历,用数组保存这些值,得到从小到大的一个数组;再次对二叉树进行中序遍历,将所遍历节点的值加上所有比它大的节点的值;对数组进行反转,即让它的值从大到小排序,然后对每个节点求和后将数组最后一个元素丢掉,因为最大的那个值不用变。

    也可以采用一次 bst 遍历,然后进行递归调用。

    代码如下:

    class Solution {  public:  int s;  void  work(TreeNode* root) {      if(!root) return;      if(!root->left && !root->right) {          root->val += s;          s = root->val;          return;      }      if(root->right) work(root->right);      root->val += s;      s = root->val;      work(root->left);  }  TreeNode* convertBST(TreeNode* root) {      s = 0;      work(root);      return root;  }  };

    转载请注明原文地址: https://ju.6miu.com/read-13884.html

    最新回复(0)