题目:给你一棵二叉搜索树,请你按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。
示例 1:
输入:root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
/**
* 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;
public TreeNode increasingBST(TreeNode root) {
if(root==null) {
return null;
}
root.right = increasingBST(root.right);
if(root.left!=null) {
TreeNode node = root.left;
root.left = null;
head = node;
while(node.right!=null)
node = node.right;
node.right = root;
return increasingBST(head);
}
else {
return root;
}
}
}
递归,很简单。
有看不明白的地方可以在评论区留言,作者会回复