給定一個二叉搜索樹(Binary Search Tree),把它轉換成爲累加樹(Greater Tree),使得每一個節點的值是原來的節點值加上全部大於它的節點值之和。node
例如:網絡
輸入: 二叉搜索樹:code
5 / \ 2 13
輸出: 轉換爲累加樹:leetcode
18 / \ 20 13
來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。get
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { private int sum = 0; public TreeNode convertBST(TreeNode root) { if (root != null) { convertBST(root.right); sum += root.val; root.val = sum; convertBST(root.left); } return root; } }