[LeetCode] 538.Convert BST to Greater Tree

来源:互联网 发布:c语言绝对值函数fabs 编辑:程序博客网 时间:2024/05/02 00:14

[LeetCode] 538.Convert BST to Greater Tree

  • 题目描述
  • 解题思路
  • 实验代码

题目描述

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

解题思路

这道题依然是要用递归的方法。想要解决这道题首先要对二叉搜索树作一个了解。二叉搜索树的特点是:若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值。知道这个特点以后这道题就得到了简化和理解。左子节点加上它父节点和右兄弟的值,父节点加上右子节点的值。这道题就得到了解决。

实验代码

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int sum = 0;    void travel(TreeNode* root) {        if (!root) return;        if (root->right)            travel(root->right);        sum += root->val;        root->val = sum;        if (root->left)            travel(root->left);    }    TreeNode* convertBST(TreeNode* root) {        travel(root);        return root;    }};
阅读全文
0 0