给你二叉树的根结点 root ,请你将它展开为一个单链表:

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

示例 1:
image

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

输入:root = []
输出:[]
示例 3:

输入:root = [0]
输出:[0]


非递归:先序遍历,然后更改左右指针

class Solution {
    public void flatten(TreeNode root) {
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        List<TreeNode> nodeList = new ArrayList<TreeNode>();

        // 第一种遍历方式
        // while (root != null || !stack.isEmpty()) {
        //     while (root != null) {
        //         nodeList.add(root);
        //         stack.push(root);
        //         root = root.left;

        //     }
        //     root = stack.pop();
        //     root = root.right;
        // }

        // 第二种遍历方式
        if (root == null) return;
        stack.push(root);
        while (!stack.isEmpty()) {
            root = stack.pop();
            nodeList.add(root);
            if (root.right != null) stack.push(root.right);
            if (root.left != null) stack.push(root.left);
        }
        int size = nodeList.size();
        for (int i = 1; i < size; i++) {
            TreeNode prev = nodeList.get(i-1);
            TreeNode curr = nodeList.get(i);
            prev.right = curr;
            prev.left = null;
        }
    }
}
posted on 2025-07-17 19:23  caoshikui  阅读(8)  评论(0)    收藏  举报