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;
        }
    }
     
  • 相关阅读:
    PTA A1005&A1006
    PTA A1003&A1004
    PTA A1001&A1002
    MOOC web前端开发笔记(二)
    MOOC web前端开发笔记(一)
    MOOC C++笔记(三):类和对象提高
    MOOC C++笔记(二):类和对象基础
    MOOC C++笔记(一):从C到C++
    linux command tee
    modbus数据格式(一)
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9784395.html
Copyright © 2011-2022 走看看