leetcode 114. 二叉树展开为链表

2023.10.22

本题第一反应就是将 原二叉树的节点值 用先序遍历的方式保存到一个集合数组中。然后再重新构造出新的二叉树。 java代码如下:

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 {
    private List<Integer> list = new ArrayList<>();
    private void preTravelsal(TreeNode cur){
        if(cur == null) return;
        list.add(cur.val);
        preTravelsal(cur.left);
        preTravelsal(cur.right);
    }
    public void flatten(TreeNode root) {
        if(root == null) return;
        preTravelsal(root);
        for(int i=1; i<list.size(); i++){
            root.right = new TreeNode(list.get(i));
            root.left = null;
            root = root.right;
        }
    }
}
相关推荐
xhbaitxl17 小时前
算法学习day38-动态规划
学习·算法·动态规划
多恩Stone17 小时前
【3D AICG 系列-6】OmniPart 训练流程梳理
人工智能·pytorch·算法·3d·aigc
历程里程碑18 小时前
普通数组----轮转数组
java·数据结构·c++·算法·spring·leetcode·eclipse
pp起床18 小时前
贪心算法 | part02
算法·leetcode·贪心算法
sin_hielo18 小时前
leetcode 1653
数据结构·算法·leetcode
2501_9011478318 小时前
面试必看:优势洗牌
笔记·学习·算法·面试·职场和发展
YuTaoShao18 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法二)排序 + 二分查找
数据结构·算法·leetcode
wangluoqi18 小时前
26.2.6练习总结
数据结构·算法
Yvonne爱编码18 小时前
链表高频 6 题精讲 | 从入门到熟练掌握链表操作
java·数据结构·链表
Q741_14718 小时前
C++ 优先级队列 大小堆 模拟 力扣 703. 数据流中的第 K 大元素 每日一题
c++·算法·leetcode·优先级队列·