题目

Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.

Example 1:

image.png

  1. Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
  2. Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

Example 2:

image.png

  1. Input: root = [5,1,7]
  2. Output: [1,null,5,null,7]

Constraints:

  • The number of nodes in the given tree will be in the range [1, 100].
  • 0 <= Node.val <= 1000

题意

将一个BST按照顺序变成一直链。

思路

简单的可以用中序遍历实现,或者用类似Morris遍历的方法也可以。


代码实现

Java

中序遍历

  1. class Solution {
  2. public TreeNode increasingBST(TreeNode root) {
  3. List<TreeNode> list = new ArrayList<>();
  4. inorder(root, list);
  5. TreeNode dummy = new TreeNode();
  6. TreeNode p = dummy;
  7. for (TreeNode node : list) {
  8. p.right = node;
  9. p = node;
  10. }
  11. return dummy.right;
  12. }
  13. private void inorder(TreeNode root, List<TreeNode> list) {
  14. if (root == null) {
  15. return;
  16. }
  17. inorder(root.left, list);
  18. list.add(root);
  19. root.left = null;
  20. inorder(root.right, list);
  21. }
  22. }

Morris

  1. class Solution {
  2. public TreeNode increasingBST(TreeNode root) {
  3. TreeNode newRoot = root;
  4. while (newRoot != null && newRoot.left != null) {
  5. newRoot = newRoot.left;
  6. }
  7. while (root != null) {
  8. if (root.left != null) {
  9. TreeNode rightMost = root.left;
  10. while (rightMost.right != null) {
  11. rightMost = rightMost.right;
  12. }
  13. rightMost.right = root;
  14. root = root.left;
  15. rightMost.right.left = null;
  16. } else if (root.right != null && root.right.left != null) {
  17. root.right = increasingBST(root.right);
  18. root = root.right;
  19. } else {
  20. root = root.right;
  21. }
  22. }
  23. return newRoot;
  24. }
  25. }