把二叉搜索树转化成更大的树-LintCode

给定二叉搜索树(BST),将其转换为更大的树,使原始BST上每个节点的值都更改为在原始树中大于等于该节点值得节点值之和(包括该节点)。

样例:

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

              5
            /   \
           2     13
Return the root of new tree

             18
            /   \
          20     13

思路
中序遍历,递归。

#ifndef C661_H
#define C661_H
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
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
    */
    TreeNode * convertBST(TreeNode * root) {
        // write your code here
        if (root == NULL)
            return NULL;
        vector<int> v;
        createVector(root, v);
        int len = v.size();
        for (int i = 0; i < len; ++i)
        {
            v[i] = accumulate(v.begin() + i, v.end(), 0);//累加得到从i位置到尾部的所有元素的和
        }
        pos = 0;
        createTree(root, v);
        return root;
    }
    //中序遍历并将节点的值存入v
    void createVector(TreeNode *root, vector<int> &v)
    {
        if (root == NULL)
            return;
        createVector(root->left, v);
        v.push_back(root->val);
        createVector(root->right, v);
    }
    //中序遍历并将节点的值置为v[pos]
    void createTree(TreeNode *root, vector<int> &v)
    {
        if (root == NULL)
            return;
        createTree(root->left, v);
        root->val = v[pos++];
        createTree(root->right, v);
    }
    int pos;
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值