알고리즘/알고리즘 문제 복기
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