力扣hot100 - 114、二叉树展开为链表

题目:思路一:通过先序遍历将元素放到一个数组中,再去遍历数组同时构造一棵二叉树。

代码略

思路二:先递归地把左子树展开为一个链表,再记录一下右子树,左子树移到右子树位置,把记录的右子树放到左子树右节点。

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 flatten(TreeNode root) {
        if(root == null){
            return;
        }
        flatten(root.left);
        flatten(root.right);
        TreeNode trmp = root.right;
        root.right = root.left;
        root.left = null;
        TreeNode cur = root;
        while(cur != null){
             if( cur.right == null){
                cur.right = trmp;
                break;
            }
            cur = cur.right;
        
        }
        return;
    }
}
相关推荐
风落青芜44 分钟前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
Pniubi5 小时前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
文丑颜不良啊15 小时前
LeetCode3041~3060题目解析
java·leetcode
罗西的思考16 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊17 小时前
LeetCode3101~3120题目解析
java·leetcode
kyle~20 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯1 天前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好1 天前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘1 天前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程1 天前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode