给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:

节点的左子树仅包含键 小于 节点键的节点。
节点的右子树仅包含键 大于 节点键的节点。
左右子树也必须是二叉搜索树。

image.png

递归

  1. var convertBST = function(root) {
  2. let pre = 0;
  3. const ReverseInOrder = (cur) => {
  4. if(cur) {
  5. ReverseInOrder(cur.right);
  6. cur.val += pre;
  7. pre = cur.val;
  8. ReverseInOrder(cur.left);
  9. }
  10. }
  11. ReverseInOrder(root);
  12. return root;
  13. };

迭代

  1. var bstToGst = function (root) {
  2. let sum = 0;
  3. const stack = [];
  4. if (root) {
  5. stack.push(root);
  6. }
  7. while (stack.length) {
  8. const node = stack.pop();
  9. if (!node) {
  10. const cur = stack.pop();
  11. cur.val += sum;
  12. sum = cur.val;
  13. continue;
  14. }
  15. node.left && stack.push(node.left);
  16. stack.push(node);
  17. stack.push(null);
  18. node.right && stack.push(node.right);
  19. }
  20. return root;
  21. };