给你一棵二叉搜索树,请你 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。
主要思想
根据中序遍历为二叉树有序遍历,所以先进行中序遍历,将中序遍历结果存储到列表中,然后再创建递增顺序搜索树
/**
* 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 {
List<Integer> list=new ArrayList();
public TreeNode increasingBST(TreeNode root) {
TreeNode ans=new TreeNode(0);
TreeNode tmp=ans;
inorder(root);
for(int value:list ){
tmp.right=new TreeNode(value);
tmp=tmp.right;
}
return ans.right;
}
public void inorder(TreeNode root){
if(root==null) return ;
inorder(root.left);
list.add(root.val);
inorder(root.right);
}
}