美文网首页
[刷题防痴呆] 0538 - 把二叉搜索树转换为累加树 (Con

[刷题防痴呆] 0538 - 把二叉搜索树转换为累加树 (Con

作者: 西出玉门东望长安 | 来源:发表于2022-03-01 00:01 被阅读0次

题目地址

https://leetcode.com/problems/convert-bst-to-greater-tree/

题目描述

538. Convert BST to Greater Tree

Given the root of 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 the sum of all keys greater than the original key in BST.

As a reminder, a binary search tree is a tree that satisfies these constraints:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
 

Example 1:


Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Example 2:

Input: root = [0,null,1]
Output: [1,null,1]

思路

  • 二叉搜索树的中序遍历即为从小到大排序. 可以先中序遍历拿到所有数值的list, 然后更新每个节点的数值.
  • 更新数值的方法为当前节点之后的所有sum更新到当前节点. 这里省时间的做法为预处理后缀和数组.
  • 中序遍历为左根右.
  • 方法2, 倒着中序遍历, 右根左, 添加一个sum. 由于右边的数比左边大, 因此当前node的数可以更新为sum.

关键点

代码

  • 语言支持:Java
/**
 * 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 {
    public TreeNode convertBST(TreeNode root) {
        List<TreeNode> list = new ArrayList<>();
        inorder(root, list);
        for (int i = 0; i < list.size(); i++) {
            TreeNode cur = list.get(i);
            int sum = cur.val;
            for (int j = i + 1; j < list.size(); j++) {
                sum += list.get(j).val;
            }
            cur.val = sum;
        }
        return root;
    }

    private void inorder(TreeNode node, List<TreeNode> list) {
        if (node == null) {
            return;
        }
        inorder(node.left, list);
        list.add(node);
        inorder(node.right, list);
    }

}


// 方法2, 倒着中序遍历
class Solution {
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if (root == null) {
            return null;
        }
        dfs(root);
        return root;
    }
    private void dfs(TreeNode node) {
        if (node == null) {
            return;
        }
        dfs(node.right);
        sum += node.val;
        node.val = sum;
        dfs(node.left);
    }
}

相关文章

网友评论

      本文标题:[刷题防痴呆] 0538 - 把二叉搜索树转换为累加树 (Con

      本文链接:https://www.haomeiwen.com/subject/bkelkrtx.html