题目传送:https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/
运行效率
代码如下
class Solution {
public void flatten(TreeNode root) {
TreeNode head = new TreeNode();
List<TreeNode> list = preOrder(root);
for (int i = 0; i < list.size()-1; i++) {
TreeNode cur = list.get(i);
TreeNode next = list.get(i + 1);
cur.left = null;
cur.right=next;
}
if(!list.isEmpty()){
list.get(list.size()-1).right=null;
}
}
//先序遍历结果
public List<TreeNode> preOrder(TreeNode root) {
List<TreeNode> result = new ArrayList<>();
//处理边界情况
if (root == null) {
return result;
}
//如果是单节点
if (root.left == null && root.right == null) {
result.add(root);
return result;
}
//1、先添加根节点
result.add(root);
//2、再添加左子树
if (root.left != null) {
List<TreeNode> list = preOrder(root.left);
result.addAll(list);
}
//2、最后添加右子树
if (root.right != null) {
List<TreeNode> list = preOrder(root.right);
result.addAll(list);
}
return result;
}
}