WELCOME TO Pluto134340小行星

清风湿润,茶烟轻扬。

46.二叉树展开为链表

114. 二叉树展开为链表
 给你二叉树的根结点 root ,请你将它展开为一个单链表:
  • 展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
  • 展开后的单链表应该与二叉树 先序遍历 顺序相同。

 示例 1:

输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]

核心思路:先通过先序遍历收集节点 存入queue ,再重新串联节点的 right 指针,同时清空 left 指针;

class Solution {
    Queue<TreeNode> queue = new LinkedList<>();
    
    public void flatten(TreeNode root) {
        // tmp 指针效果,逐个后移
        TreeNode tmp = root;
        xianxv(root);    // 先序遍历 存入队列
        while(tmp!=null){
            tmp.right = queue.poll();
            tmp.left=null;
            tmp = tmp.right;
        }
    }

    // 先序遍历(根-左-右),将节点存入队列
    public void xianxv(TreeNode root) {
        if (root == null) return;
        queue.offer(root);
        xianxv(root.left);
        xianxv(root.right);
    }
}

【结合了链表遍历、树的queue】

posted @ 2026-01-28 10:47  Pluto134340  阅读(2)  评论(0)    收藏  举报