递增顺序搜索树
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]
输入:root = [5,1,7]
输出:[1,null,5,null,7]
2、算法描述
核心思想:
题中给出了树是一个顺序搜索树,那么说明左边 > 中间 > 右边,我们可以采用中序遍历的方式进行求解
3、代码实现
(1)、树结构代码
package com.bean;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode() {
}
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
(2)、算法代码
package com.java;
import com.bean.TreeNode;
import java.util.*;
public class Day25_Solution {
public TreeNode increasingBST(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
inOrder(root,list);
TreeNode newRoot = new TreeNode(list.get(0));
TreeNode currentNode = newRoot;
for (int i=1;i<list.size();i++) {
currentNode.right = new TreeNode(list.get(i));
currentNode = currentNode.right;
}
return newRoot;
}
public void inOrder(TreeNode root,ArrayList<Integer> list) {
if (root != null) {
inOrder(root.left,list);
list.add(root.val);
inOrder(root.right,list);
}
}
}
(3)、测试类代码
package com.test;
import com.bean.TreeNode;
import com.java.Day25_Solution;
public class Test25 {
public static void main(String[] args) {
Day25_Solution solution = new Day25_Solution();
TreeNode node5 = new TreeNode(5);
TreeNode node3 = new TreeNode(3);
TreeNode node6 = new TreeNode(6);
TreeNode node2 = new TreeNode(2);
TreeNode node4 = new TreeNode(4);
TreeNode node8 = new TreeNode(8);
TreeNode node1 = new TreeNode(1);
TreeNode node7 = new TreeNode(7);
TreeNode node9 = new TreeNode(9);
node5.left = node3;
node5.right = node6;
node3.left = node2;
node3.right = node4;
node6.left = null;
node6.right = node8;
node2.left = node1;
node8.left = node7;
node8.right = node9;
TreeNode root = solution.increasingBST(node5);
while (root != null) {
System.out.println(root.val);
root = root.right;
}
}
}