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);    }}



原创粉丝点击