二叉搜索树中序遍历

难度简单

题目描述

给你一棵二叉搜索树,请你按中序遍历将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。
image.png

解题思路

参考:剑指 Offer 36. 二叉搜索树与双向链表

Code

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. TreeNode head, pre;
  18. public TreeNode increasingBST(TreeNode root) {
  19. if (root == null) {
  20. return head;
  21. }
  22. recurBST(root);
  23. return head;
  24. }
  25. public void recurBST(TreeNode cur) {
  26. if (cur == null) {
  27. return;
  28. }
  29. recurBST(cur.left);
  30. if (pre == null) {
  31. head = cur;
  32. } else {
  33. pre.right = cur;
  34. }
  35. cur.left = null;
  36. pre = cur;
  37. recurBST(cur.right);
  38. }
  39. }