Convert BST to Greater Tree

来源:互联网 发布:求数组最大最小值 编辑:程序博客网 时间:2024/06/06 03:57

问题描述: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.

样例

Given a binary search Tree `{5,2,3}`:

              5            /   \           2     13

Return the root of new tree

             18            /   \          20     13
题目大意:给定一棵二叉查找树,将其转化为“Greater Tree”,原始BST中的每一个节点都替换为不小于其本身的各节点的和。

实现思路:树的最右边的节点的值不变,其根节点的值等于根节点加上右子树的值之和,左子树的值等于左子树的数值加上上一步得到的根节点的数值,按照这个规则将二叉树的所有节点的值替换一遍。逆序遍历,先遍历右子树,处理当前节点,再遍历左子树。

实现代码:/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root the root of binary tree
     * @return the new root
     */
    int sum=0;
    void travel(TreeNode* root)
    {
        if(root==NULL)
        return;
        travel(root->right);
        sum+=(root->val);
        root->val=sum;
        travel(root->left);
    }
    TreeNode* convertBST(TreeNode* root) {
        // Write your code here
        if(root==NULL)
        return NULL;
        travel(root);
        return root;
    }
};

做题感想:一看到二叉排序树,直接可以想到中序遍历,这个题和普通中序遍历不同的地方在于,它要把整棵树中比自己大的节点加起来。

原创粉丝点击