前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode538 Convert BST to Greater Tree

leetcode538 Convert BST to Greater Tree

作者头像
用户1665735
发布2018-06-21 12:16:50
4130
发布2018-06-21 12:16:50
举报
文章被收录于专栏:kevindroidkevindroid

题目

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 简单来说,就是把一棵BST的所有节点的值转化为其本身加上所有比它的节点的和。

解题思路

当看到这个题目的时候,我是懵逼的。很明显存在重复计算和,所以我一开始想的是动态规划,然后我花了一个图。

这里写图片描述
这里写图片描述

红色代表节点应该被访问的顺序,定睛一看,这似乎和中序遍历差不多啊。只不过中序遍历是左中右,而这里是右中左而已。 为了追求效率,采取非递归的遍历,设置一个值保存之前的和。

代码语言:javascript
复制
public class leetcode538 {
    public TreeNode convertBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode p = root;
        int res = 0;
        while (!stack.isEmpty()||p!=null){
            if(p!=null) {
                stack.push(p);
                p = p.right;
            }
            else {
                p = stack.pop();
                int temp = p.val;
                p.val += res;
                res += temp;
                p = p.left;
            }
        }
        return root;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年04月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解题思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档