力扣114.二叉树展开为链表

114.二叉树展开为链表

思路:
  1. 根据题意,展开后的单链表应该与二叉树前序遍历顺序相同,所以使用前序遍历把二叉树的元素放入链表中
  2. 根据示意图,将新二叉树的右边全部置为链表中的元素,左边全部置为空即可
代码实现
/**
 * 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) {
        List<TreeNode> list = new LinkedList<>();
        preorder(root, list);
        if (root == null) return;
        int size = list.size();
        
        for (int i = 1; i < size; i++) {
            root.right = list.get(i);
            root.left = null;
            root = root.right;
        }
    }

    public void preorder(TreeNode root, List<TreeNode> list) {
        if (root == null) return;
        list.add(root);
        preorder(root.left, list);
        preorder(root.right, list);
    }
}

你可能感兴趣的:(链表,leetcode,数据结构)