Leetcode - 538. Convert BST to Greater Tree

Leetcode - 538. Convert BST to Greater Tree_第1张图片

tag 上说是 tree 类型的题目,但我觉得这更像是一个 backtracking的题目

解法:

因为题目要求所有比node.val大得值都要加上去,而这是一颗BST,所以比node.val大的值肯定都在node的右边,


base:

if is_leaf(node):

     add the value of node into carry

    set the value of the node = to carry


step:

if there is right node

'order is important here, you have to go to right firstto allocate all value greater than node.val' recursion(root.right,carry)


if there is left node:

since all left node is sure smaller than node.val, all we need to do here is simpliy add the number into all left node'val




Leetcode - 538. Convert BST to Greater Tree_第2张图片

你可能感兴趣的:(Leetcode - 538. Convert BST to Greater Tree)