您的位置:首页 > 编程语言

leetcode编程记录8 #107 Binary Tree Level Order Traversal II

2017-10-21 01:56 585 查看

leetcode编程记录8 #107 Binary Tree Level Order Traversal II

标签(空格分隔): 日记

这次是一道比较简单的题目,题目如下:

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:
vector<int> allNode;
TreeNode* convertBST(TreeNode* root) {
Traversal(root);
sum(root);
return root;

}
void sum(TreeNode* root) {

if (root != NULL) {
sum(root->right);
sum(root->left);
int oringin = root->val;
for (int i = 0; i < allNode.size(); ++i)
{
if (oringin < allNode[i]) {
root->val += allNode[i];
}
}

}

}
void Traversal(TreeNode* root) {
if (root != NULL) {
Traversal(root->left);
Traversal(root->right);
allNode.push_back(root->val);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: