zoukankan      html  css  js  c++  java
  • Leetcode538.-Convert BST to Greater Tree-Easy

    题目:

    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.

    思路:

    每个结点值加上所有比它大的结点值总和当作新的结点值。

    初始化sum值 = 0

    因为inorder traversal (left->root->right)结果是non decreasing 递增数列,那么逆过来right->root->left,就可以得到递减数列, 每遍历到一个结点更新sum值,并将更新后的sum值赋给当前结点,从而保证,在当前结点,所有比他大的结点都访问过了,并且sum值就是所有比他大的结点值的总合。

    代码:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        private int sum = 0;
        
        public TreeNode convertBST(TreeNode root) {
            dfs(root);
            return root;
        }
        private void dfs(TreeNode root) {
            if(root == null) return;
            dfs(root.right);
            sum += root.val;
            root.val = sum;
            dfs(root.left);
        }
    }
  • 相关阅读:
    单表查询
    解读python中SocketServer源码
    C++实训(2.3)
    C++实训(2.2)
    C++实训(2.1)
    C++实训(1.3)
    C++实训(1.1)
    顺序表的实现,在vs2019上运行成功
    p243_5(3)
    自考新教材-p176_5(2)
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/13437459.html
Copyright © 2011-2022 走看看