更多题解尽在 https://sugar.matrixlab.dev/algorithm 每日更新。
组队打卡,更多解法等你一起来参与哦!
LeetCode 114. 二叉树展开为链表 ,难度中等。
DFS
解题思路:先用 DFS 遍历二叉树,将树的结果存放在 List 中,然后更新原先的二叉树。
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void preorderTraversal(List<TreeNode> traList, TreeNode root) {
if (root == null) {
return;
}
traList.add(root);
preorderTraversal(traList, root.left);
preorderTraversal(traList, root.right);
}
public void flatten(TreeNode root) {
List<TreeNode> traList = new ArrayList<>();
preorderTraversal(traList, root);
TreeNode temp = root;
for (int i = 1; i < traList.size(); ++i) {
temp.right = traList.get(i);
temp.left = null;
temp = temp.right;
}
}
}