LeetCode Hot100 114.二叉树展开为链表

题目

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

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

方法一:先前序遍历,然后再修改左右指针

class Solution {
    public void flatten(TreeNode root) {
        List list = new ArrayList();
        preorderTraversal(root, list);
        int size = list.size();
        for(int i = 1; i < size; i++) {
            TreeNode pre = list.get(i - 1), cur = list.get(i);
            pre.right = cur;
            pre.left = null;
        }
    }
    private void preorderTraversal(TreeNode root, List list) {
        if (root == null)
            return;
        list.add(root);
        preorderTraversal(root.left, list);
        preorderTraversal(root.right, list);
    }
}

LeetCode Hot100 114.二叉树展开为链表_第1张图片

方法二:寻找前驱节点

LeetCode Hot100 114.二叉树展开为链表_第2张图片

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

LeetCode Hot100 114.二叉树展开为链表_第3张图片

你可能感兴趣的:(算法刷题-二叉树,leetcode,链表,算法)