解法一:先序遍历+累加和

先进行先序遍历,得到升序数组,然后反转数组,计算累加和。

  1. import java.util.Collections;
  2. import java.util.ListIterator;
  3. /**
  4. * Definition for a binary tree node.
  5. * public class TreeNode {
  6. * int val;
  7. * TreeNode left;
  8. * TreeNode right;
  9. * TreeNode(int x) { val = x; }
  10. * }
  11. */
  12. class Solution {
  13. List<TreeNode> nodeList;
  14. public TreeNode convertBST(TreeNode root) {
  15. nodeList = new LinkedList<>();
  16. inOrder(root);
  17. addSum();
  18. return root;
  19. }
  20. private void addSum() {
  21. Collections.reverse(nodeList);
  22. int sum = 0;
  23. int temp;
  24. for (TreeNode i : nodeList) {
  25. temp = i.val;
  26. i.val += sum;
  27. sum += temp;
  28. }
  29. }
  30. private void inOrder(TreeNode root) {
  31. if (root == null) {
  32. return;
  33. }
  34. inOrder(root.left);
  35. nodeList.add(root);
  36. inOrder(root.right);
  37. }
  38. }

解法二:反中序遍历

采用一种反中序遍历“右中左”,以降序的方式访问结点,并保存上一次的结点值,不断累加。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. // 上一个遍历过的结点的值
  12. private int lastNum;
  13. public TreeNode convertBST(TreeNode root) {
  14. antiInOrder(root);
  15. return root;
  16. }
  17. private void antiInOrder(TreeNode root) {
  18. if (root == null) {
  19. return;
  20. }
  21. antiInOrder(root.right);
  22. root.val += lastNum;
  23. lastNum = root.val;
  24. antiInOrder(root.left);
  25. }
  26. }