博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
538. Convert BST to Greater Tree
阅读量:7287 次
发布时间:2019-06-30

本文共 2283 字,大约阅读时间需要 7 分钟。

题目描述:

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     13Output: The root of a Greater Tree like this:             18            /   \          20     13

解题思路:

起初的思路时间复杂度不好,借鉴别人的思路,DFS是个更好的方法。

先对右儿子进行处理,对值进行累加,再对父节点进行处理,最后对左儿子进行处理。

代码:

起初的代码:

1 /** 2  * Definition for a binary tree node. 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     TreeNode* convertBST(TreeNode* root) {13         if (root == NULL)14             return NULL;15         root->right = convertBST(root->right);16         if (root->right != NULL)17             root->val = root->val + findLeft(root->right);18         if (root->left != NULL) {19             TreeNode* tmp = findR(root->left);20             tmp->val = tmp->val + root->val;21         }22         root->left = convertBST(root->left);23         /*if (root->left != NULL)24             root->left->val = root->left->val + root->val;*/25         return root;26     }27     int findLeft(TreeNode* root) {28         while (root->left != NULL) {29             root = root->left;30         }31         return root->val;32     }33     TreeNode* findR(TreeNode* root) {34         while (root->right != NULL) {35             root = root->right;36         }37         return root;38     }39 };
View Code

DFS:

1 /** 2  * Definition for a binary tree node. 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     TreeNode* convertBST(TreeNode* root) {13         int sum = 0;14         DFS(root, sum);15         return root;16     }17     void DFS(TreeNode* root, int& sum) {18         if (!root) 19             return;20         DFS(root->right, sum);21         sum += root->val;22         root->val = sum;23         DFS(root->left, sum);24     }25 };
View Code

 

转载于:https://www.cnblogs.com/gsz-/p/9564354.html

你可能感兴趣的文章
Linux iptables:规则组成
查看>>
HDU 4442 Physical Examination【水题】【思维题】
查看>>
NET 命令 常用方法!
查看>>
我的友情链接
查看>>
memcached
查看>>
谁搞死了你的软件?
查看>>
Promise 对象
查看>>
Windows快速添加IP地址
查看>>
AS3.0 事件流
查看>>
“将截断字符串或二进制数据。语句已终止……”问题的解决
查看>>
红苹果IP代理软件 v6.2
查看>>
Centos5.x & Centos6.x 使用mail命令发邮件以及如何伪造发件人
查看>>
JavaScript系列:ECMAScript原始类型
查看>>
centos反编译APK包
查看>>
CSS系列:CSS中盒子的浮动与定位
查看>>
windows 用户用户组迁移
查看>>
Linux系统扩充2
查看>>
linux新手的心得
查看>>
我的友情链接
查看>>
zabbix表字段类型和value type问题
查看>>