leetcode.com/problems/flatten-binary-tree-to-linked-list
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는 리스트의 다음 인덱스에 있는 노드를 가리키게 해준다.
'알고리즘 문제풀이 > LeetCode' 카테고리의 다른 글
[LeetCode 104] Maximum Depth of Binary Tree with JAVA (0) | 2021.04.25 |
---|---|
[LeetCode 200] Numbers of Islands with JAVA (0) | 2021.04.25 |
[LeetCode 101] Symmetric Tree with JAVA (0) | 2021.04.16 |
[LeetCode 20] Valid Parentheses with JAVA (0) | 2021.04.11 |
[LeetCode 647] Palindromic Substrings with JAVA (BruteForce) (0) | 2021.04.10 |