본문 바로가기

알고리즘 문제풀이/LeetCode

[LeetCode 114] flatten-binary-tree-to-linked-list with JAVA

leetcode.com/problems/flatten-binary-tree-to-linked-list

 

Flatten Binary Tree to Linked List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Given the root of a binary tree, flatten the tree into a "linked list":

  • The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
  • The "linked list" should be in the same order as a pre-order traversal of the binary tree.

 

Example 1:

Input: root = [1,2,5,3,4,null,6] Output: [1,null,2,null,3,null,4,null,5,null,6]

Example 2:

Input: root = [] Output: []

Example 3:

Input: root = [0] Output: [0]

 

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -100 <= Node.val <= 100

 

import java.util.*;

/**
 * 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 {
    static List<TreeNode> arr = new ArrayList<>();
    public void flatten(TreeNode root) {
        preorder(root);
        TreeNode prev = arr.get(0);
        for (int i = 1; i < arr.size(); i++){
            TreeNode cur = arr.get(i);
            prev.left = null;
            prev.right = cur;
            prev = cur;
        }
        prev.left = null;
        prev.right = null;
    }
    public void preorder(TreeNode root) {
        if (root == null) return;
        arr.add(root);
        preorder(root.left);
        preorder(root.right);
    }
}

1. 어려웠던 점:

  - preorder, inorder, postorder에 대해 잘 알고 있다고 생각했으나, 미진했음

 

2. 알게된 점:

  - tree traversal 복습

 

3. 알고리즘 풀이:

preorder로 트리를 순회해 리스트에 담아둔다.

리스트를 돌며, left에는 null, right는 리스트의 다음 인덱스에 있는 노드를 가리키게 해준다.