题目链接:LeeCode114二叉树展开为链表
题目描述:
先前序遍历将结果存到list里面,再遍历list将数据拼接到root上
public static void flatten(TreeNode root) {
Stack<TreeNode> nodes=new Stack<>();
List<TreeNode> list=new ArrayList<>();
TreeNode node=root;
while (!nodes.isEmpty() || node != null) {
if (node != null) {
nodes.push(node);
list.add(node);
node=node.left;
}else{
node=nodes.pop();
node=node.right;
}
}
for (int i = 1; i < list.size(); i++) {
if(root.left!=null) root.left=null;
TreeNode r=list.get(i);
root.right=r;
root=root.right;
}
}
}