leetcode538. 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.java

Example:this

Input: The root of a Binary Search Tree like this:code

5
        /   \
       2     13

Output: The root of a Greater Tree like this:递归

18
        /   \
      20     13

现有一棵二叉搜索树,须要将二叉搜索树上每一个节点的值转化为大于等于该节点值的全部值的和。it

思路和代码

这一题能够经过递归的思路来计算出每一个节点的目标值。能够知道,每个节点大于当前节点的值寄存于距离本身最近的左节点以及本身的右节点中。所以计算每一个节点时,须要传入当前节点以及距离本身最近的左父节点。class

public TreeNode convertBST(TreeNode root) {  
    if (root == null) {  
        return null;  
    }  
    return convertBST(root, null);  
}  
  
public TreeNode convertBST(TreeNode cur, TreeNode leftParent) {  
    TreeNode newCur = new TreeNode(cur.val);  
    if (leftParent != null) {  
        newCur.val += leftParent.val;  
    }  
    if (cur.right != null) {  
        newCur.right = convertBST(cur.right, leftParent);  
        cur.val += cur.right.val;  
        newCur.val += cur.right.val;  
    }  
    if (cur.left != null) {  
        TreeNode newLeft = convertBST(cur.left, newCur);  
        cur.val += cur.left.val;  
        newCur.left = newLeft;  
    }  
    return newCur;  
}
相关文章
相关标签/搜索