把二叉搜索树转化成更大的树-LintCode
来源:互联网 发布:希尔排序算法详细 编辑:程序博客网 时间:2024/05/16 01:12
给定二叉搜索树(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
阅读全文
0 0
- 把二叉搜索树转化成更大的树-LintCode
- 538. Convert BST to Greater Tree 二叉搜索树转化为更大的树
- LintCode SortedArrayToBST 把排序数组转换为高度最小的二叉搜索树
- lintcode-把排序数组转换为高度最小的二叉搜索树-177
- 把排序数组转换为高度最小的二叉搜索树(LintCode)
- LintCode:把排序数组转换为高度最小的二叉搜索树
- lintCode(177)——把排序数组转换为高度最小的二叉搜索树
- LintCode:把排序数组转换为高度最小的二叉搜索树
- lintcode,把排序数组转换为高度最小的二叉搜索树
- LintCode | 177. 把排序数组转换为高度最小的二叉搜索树
- LintCode 把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树-LintCode
- lintcode——把排序数组转换为高度最小的二叉搜索树
- lintcode把排序数组转换为高度最小的二叉搜索树
- LintCode-把排序数组转换为高度最小的二叉搜索树
- lintcode 把排序数组转换为高度最小的二叉搜索树
- LintCode 把排序数组转换为高度最小的二叉搜索树
- LintCode 177-把排序数组转换为高度最小的二叉搜索树
- 还未入门的程序猿的学习经历
- 课堂小笔记
- 码云+ webpack
- Jenkins持续化部署问题收集
- 如何免费获取ssl证书,https证书
- 把二叉搜索树转化成更大的树-LintCode
- idea如何设置类头注释和方法注释
- 2017/11/15C语言作业
- 别让Android Studio的缓存文件占据你的C盘
- 母线同杆架设数据结构转换小计
- 定义一个图形类及其子类(三角形类和矩形类),分别计算其面积和周长
- JS文件中的中文在网页上显示为乱码解决方法
- python django-blog-zinnia
- mysql死锁问题分析