【详细整理】114. 二叉树展开为链表

593 阅读1分钟

题目

难度中等

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

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

思路一、暴力解法

暴力解法,先用res储存先序遍历结果,然后用一个for循环构建单链表。

class Solution {
    public void flatten(TreeNode root) {
        ArrayList<TreeNode> res = new ArrayList<>();
        qianxu(root,res);
        for(int i = 1; i < res.size(); ++i){
            TreeNode a = res.get(i-1);
            TreeNode b = res.get(i);
            a.right = b;
            a.left = null;
        }

    }
    public void qianxu(TreeNode root,ArrayList<TreeNode> res){
        if(root == null){return ;}
        res.add(root);
        qianxu(root.left,res);
        qianxu(root.right,res);
    }
}

image.png

思路二、在树上进行操作

就是把左树接到右边: 1、找到左树的最右节点 2、将右树接到最右节点后 3、将左树挪到右边,左树置空 4、对每一个节点进行操作

class Solution {
    public void flatten(TreeNode root) {
       while(root != null){
        if(root.left == null){
            root = root.right;
        }else{
            TreeNode pre = root.left;
            while(pre.right != null){
                pre = pre.right;
            }
            pre.right = root.right;
            root.right = root.left;
            root.left = null;
            root = root.right;
        }

    }
    }
}

image.png