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

    算法分析:

    用"中序遍历"的方式访问每个节点的值,并将该节点的值累加到一个 int sum 变量上,并用该 sum 变量更新该节点的值。要注意的是,此处的中序遍历是先遍历右子树,再访问根节点,然后再遍历左子树(因为 BST 根节点的值小于右子树所有节点的值,大于左子树所有节点的值)。

    Java 算法实现:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        int sum=0;
        public TreeNode convertBST(TreeNode root) {
            sum=0;
            addSum(root);
            return root;
        }
        
        public void addSum(TreeNode root){
        	if(root!=null){
        		addSum(root.right);
        		sum+=root.val;
        		root.val=sum;
        		addSum(root.left);
        		
        	}
        }
    }
  • 相关阅读:
    hdu 1296
    hdu 2101
    hdu 2100
    codeforces 3C
    codeforces 2A
    codeforces 1B
    codeforces 811B
    关于sws_scale() 段错误
    cf 1288 D. Minimax Problem (好题)(二分+二进制表状态+枚举)
    opencv4 鼠标事件 鼠标画线条
  • 原文地址:https://www.cnblogs.com/dongling/p/6579689.html
Copyright © 2011-2022 走看看