zoukankan      html  css  js  c++  java
  • [LC] 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

    Example 1:

    Input : {5,2,13}
                  5
                /   
               2     13
    Output : {18,20,13}
                 18
                /   
              20     13
    

    Example 2:

    Input : {5,3,15}
                  5
                /   
               3     15
    Output : {20,23,15}
                 20
                /   
              23     15


    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    
    public class Solution {
        /**
         * @param root: the root of binary tree
         * @return: the new root
         */
        public TreeNode convertBST(TreeNode root) {
            // write your code here
            int[] sum = new int[]{0};
            helper(root, sum);
            return root;
        }
        
        private void helper(TreeNode root, int[] sum) {
            if (root == null) {
                return;
            }
            helper(root.right, sum);
            sum[0] += root.val;
            root.val = sum[0];
            helper(root.left, sum);
        }
    }
  • 相关阅读:
    HDU 1856 More is better
    并查集模板
    HDU 1325 Is It A Tree?
    HDU 1272 小希的迷宫
    CodeVS 2639 约会计划
    POJ 1163 数字三角形
    HDU 1232 畅通工程
    HDU 1213 How Many Tables
    树形结构打印二叉树
    网址收藏
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12549881.html
Copyright © 2011-2022 走看看