问题描述
给定一个树,按顺序重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
输入:[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
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class Solution{
public TreeNode solution(TreeNode node){
if(null == node){
return null;
}
List<Integer> data = midOrder(node);
TreeNode result = new TreeNode(data.get(0));
TreeNode cur = result;
for(int i = 1; i < data.length; i++){
TreeNode right = new TreeNode(data.get(i));
cur.right = right;
cur = cur.right;
}
return result;
}
public List<Integer> midOrder(TreeNode node){
List<Integer> list = new ArrayList<Integer>();
LinkedList stack = new ArrayList<Integer>();
while(!stack.isEmpty() || null != node){
if(null != node){
stack.push(node);
node = node.left;
}else{
node = stack.pop();
list.add(node.val);
node = node.right;
}
}
}
}