LeetCode—114. Flatten Binary Tree to Linked List
题目
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
思路及方法
前序遍历二叉树,存到列表里,在建立新书。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
List<TreeNode> list = new ArrayList<>();
if(root==null) return;
preOrder(list, root);
int i=0;
for(i=0; i<list.size()-1; i++){
list.get(i).left = null;
list.get(i).right = list.get(i+1);
}
list.get(i).left = null;
list.get(i).right = null;
}
public void preOrder(List list, TreeNode node){
if(node==null) return;
list.add(node);
if(node.left!=null) preOrder(list, node.left);
if(node.right!=null) preOrder(list, node.right);
}
}