-
LeetCode - 114. Flatten Binary Search Tree알고리즘/알고리즘 문제 복기 2021. 5. 29. 11:38
https://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
뭔가 순서를 뒤집는 것이 있을때 스택을 사용하면 편리하다.
Preorder는 Root -> Left -> Right순으로 이어진다.
Pseudo Code
void flatten(TreeNode root) { Stack<TreeNode> s; s.push(root) while(stack is not empty) current_node = s.pop(); if(current_node.right != null) s.push(current_node.right); if(current_node.left != null) s.push(currnet_node.left); if(stack is not empty) current_node.right = s.peek(); current_node.left = null; }
Answer
Answer2
Solution에서 가져온 코드인데 속도도 빠르고 간단하다
근데 이해가 가지 않아 나중에 한번 더 봐야할듯하다.
Reference
https://www.youtube.com/watch?v=vssbwPkarPQ
'알고리즘 > 알고리즘 문제 복기' 카테고리의 다른 글
학급회장 뽑기 (0) 2021.09.10 하노이탑 (0) 2021.08.30 Leetcode - 105. Construct Tree from Preorder and Inorder Traversal (0) 2021.05.27 LeetCode - 96. Unique Binary Search Tree (0) 2021.05.18 LeetCode - 94. Binary Tree Inorder Traversal (0) 2021.04.26