给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
示例 :
输入:[5,3,6,2,4,null,8,1,null,null,null,7,9]
5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9
输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
1
\
2
\
3
\
4
\
5
\
6
\
7
\
8
\
9
提示:
给定树中的结点数介于 1 和 100 之间。
每个结点都有一个从 0 到 1000 范围内的唯一整数值。
使用中序遍历的方式进行查找元素,然后进行数据元素的构建
import java.util.ArrayList;
import java.util.List;
public class IncreasingBSTTest {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(5);
TreeNode t2 = new TreeNode(3);
TreeNode t3 = new TreeNode(6);
TreeNode t4 = new TreeNode(2);
TreeNode t5 = new TreeNode(4);
TreeNode t6 = new TreeNode(8);
TreeNode t7 = new TreeNode(1);
TreeNode t8 = new TreeNode(7);
TreeNode t9 = new TreeNode(9);
t1.left = t2;
t1.right = t3;
t2.left = t4;
t2.right = t5;
t3.right = t6;
t4.left = t7;
t6.left = t8;
t6.right = t9;
increasingBST(t1);
}
public static TreeNode increasingBST(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return null;
}
dfs(root, list);
TreeNode dummyNode = new TreeNode(-1);
TreeNode tempNode = dummyNode;
for (Integer integer : list) {
TreeNode temp = new TreeNode(integer);
tempNode.right = temp;
tempNode = tempNode.right;
}
return dummyNode.right;
}
private static void dfs(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
if (root.left != null) {
dfs(root.left, list);
}
list.add(root.val);
if (root.right != null) {
dfs(root.right, list);
}
}
}
这次使用的是中序遍历得到树元素结点,然后对元素结点进行重新构建