二叉搜索树中序遍历
难度简单
题目描述
给你一棵二叉搜索树,请你按中序遍历将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。
解题思路
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode head, pre;
public TreeNode increasingBST(TreeNode root) {
if (root == null) {
return head;
}
recurBST(root);
return head;
}
public void recurBST(TreeNode cur) {
if (cur == null) {
return;
}
recurBST(cur.left);
if (pre == null) {
head = cur;
} else {
pre.right = cur;
}
cur.left = null;
pre = cur;
recurBST(cur.right);
}
}