[LeetCode]538. 把二叉搜索树转换为累加树

题目

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

例如:

输入: 二叉搜索树:

              5
            /   \
           2     13

输出: 转换为累加树:

             18
            /   \
          20     13

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

  • 使用 反中序遍历 即右根左的顺序遍历
  • 这样只需遍历一遍,因为二叉搜索树的性质保证了是从大到小遍历,每次更新累加值,并加到当前节点上更新节点值即可。

代码

/**
 * 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;
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/11809632.html