前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发优快云,mcf171专栏。这次比赛略无语,没想到前3题都可以用暴力解。
博客链接:mcf171的博客
——————————————————————————————
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这个题目也挺简单的,使用后序遍历即可。先遍历右节点,再遍历左节点即可。
public class Solution {
public TreeNode convertBST(TreeNode root) {
help(root, 0);
return root;
}
public int help(TreeNode root, int plus){
if(root == null) return 0;
int right = help(root.right, plus);
int left = help(root.left,plus + right + root.val);
int result = right + left + root.val;
root.val = plus + right + root.val;
return result;
}
}