zoukankan      html  css  js  c++  java
  • [LeetCode] 538. Convert BST to Greater Tree

    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

    题意:给定一个二叉搜索树,把它转换成为累加树,使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
    做树的题一定要利用条件,就是特别的给了一个什么样的树,这个树有什么特性
    二叉搜索树的特点是 右>根>左,也就是说中序有序,我们把中序倒过来就正好是从大到小的
    什么意思呢,就是当你遍历到某个节点的时候,比它大的都已经遍历完了,我们只需维护一个max就行
    class Solution {
        private int max = 0;
        private void convert(TreeNode root) {
            if (root == null)
                return;
            convert(root.right);
            root.val += max;
            max = root.val;
            convert(root.left);
        }
        public TreeNode convertBST(TreeNode root) {
            convert(root);
            return root;
        }
    }
     
  • 相关阅读:
    数据结构之静态库动态库
    数据结构之二叉树
    数据结构之学习大纲
    Unix高级编程之文件及目录
    Unix高级编程之标准IO
    Unix高级编程之文件IO
    Unix高级编程之进程控制
    Unix高级编程之进程环境
    内置支持类(RegExp)
    获取DOM元素的三种方法
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9784395.html
Copyright © 2011-2022 走看看