leetcode
来源:互联网 发布:alias for mac 编辑:程序博客网 时间:2024/06/15 01:15
题目
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
题意
给定一个二叉查找树,将转化为更大的树,在这棵大树中,每个原来结点的键值都变为 (原来的键值 + 所有比该键原来键值大的键之和)。
分析及解答
解法1:(从大到小,利用队列,累积)
- 【处理的顺序:从小到大】根据题意,确定积累的规则,和处理的顺序,从大到小处理,这样做的好处是后面的小数能够利用前面计算累积的结果(sum),同时确保小数只看到比其大的数即可,因为其只依赖于比其大的数。
public class Solution {public TreeNode convertBST(TreeNode root) {if (root == null) {return null;}Queue<TreeNode> queue = new LinkedList<>();initQueue(root, queue);TreeNode pre = queue.poll();TreeNode current = queue.poll();while(current != null){current.val = current.val + pre.val; pre = current;current = queue.poll();}return root;}public void initQueue(TreeNode root, Queue<TreeNode> queue) {if (root == null) {return;}initQueue(root.right, queue);queue.add(root);initQueue(root.left,queue);}}
解法2:(思想同上,遍历 + 全局变量)
public class Solution { int sum = 0; public TreeNode convertBST(TreeNode root) { convert(root); return root; } public void convert(TreeNode cur) { if (cur == null) return; convert(cur.right); cur.val += sum; sum = cur.val; convert(cur.left); }}
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Currency Exchange (SPFA)
- jdk 源码分析(20)java NIO包简单分析
- JDK1.8 List使用心得记录
- ORA-00845 : MEMORY_TARGET not supported on this system(调大数据库内存无法启动)
- CSU-ACM2017暑期训练12-KMP E
- leetcode
- R实战:【基本类型】字符串与类型转换
- mybatis-generator插件自动生成代码
- Linux 中如何辨别当前所安装jdk是32位还是64位
- 练习 3-1 在上面有关折半查找的例子中,while循环语句内共执行了两次测试,其实只要一次就足够(代价是将更多的测试在循环外执行)。重写该函数,使得在循环内部只执行一次测试。
- Zynq-Linux移植学习笔记之19-启动加载与固化
- AbstractQueuedSynchronizer源码分析一(独占锁部分,公平非公平)
- pat1005. 继续(3n+1)猜想
- 53. Maximum Subarray