114. 二叉树展开为链表
小于 1 分钟
114. 二叉树展开为链表中等
解法:
先序遍历树,将结果存入数组中,再通过根节点构造树
class Solution {
ArrayList<TreeNode> list = new ArrayList<>();
public void flatten(TreeNode root) {
if (root == null)
return;
TreeNode node = root;
order(root);
for (int i = 0; i < list.size(); i++) {
node.left = null;
node.right = list.get(i);
node = node.right;
}
}
public void order(TreeNode node) {
if (node.left != null) {
list.add(node.left);
order(node.left);
}
if (node.right != null) {
list.add(node.right);
order(node.right);
}
}
}
Powered by Waline v2.15.5