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;  
}
相關文章
相關標籤/搜索