JAVA/Coding Test Study
[Easy] LeetCode - no.226 Invert Binary Tree : Java
♡˖GYURI˖♡
2024. 10. 23. 16:12
728x90
문제
이진 트리의 root 노드가 주어졌을 경우, 해당 트리의 좌우를 반전시킨 후 root를 반환할 것
풀이
참고
LeetCode 226(Invert Binary Tree, java)
0. 문제 https://leetcode.com/problems/invert-binary-tree/ Invert Binary Tree - 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 1. 문제
devraphy.tistory.com
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return root;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
- 재귀 사용
- root.left와 root.right를 swap
- root.left를 노드로 재귀 호출 & root.right를 노드로 재귀 호출
- root 반환
- 시간복잡도 : O(N)