๐งฉ Algorithm/DFS BFS
[LeetCode] 226๋ฒ: Invert Binary Tree
HelloRabbit
2023. 3. 10. 14:09
728x90
Hint
1. DFS ์๊ณ ๋ฆฌ์ฆ ์ฌ์ฉํด์ผํจ
2. ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ์ ์์ ๋ ธ๋๊ฐ ์๋ค๋ฉด ๋ฐ๊ฟ์น๊ธฐ ํด์ฃผ๋ฉด ๋จ
LeetCode 226๋ฒ: Invert Binary Tree (ํ์ด๋ณด๊ธฐ)
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(root):
# ๋
ธ๋์ธ์ง ํ์ธ. ๋
ธ๋๊ฐ ์๋๋ผ๋ฉด None ๊ฐ์ด๊ธฐ ๋๋ฌธ์ not์ ํด์ค์ผ True๊ฐ ๋จ
if not root:
return root # ๋
ธ๋๊ฐ ์๋๊ธฐ ๋๋ฌธ์ ๋ฐ๊ฟ์น๊ธฐ ์ํ๊ณ ๊ทธ๋ฅ ๋ฐํ
dfs(root.left) # ์ผ์ชฝ ๋
ธ๋์ ์์ ๋
ธ๋ ๋ค์ง๊ธฐ
dfs(root.right) # ์ค๋ฅธ์ชฝ ๋
ธ๋์ ์์ ๋
ธ๋ ๋ค์ง๊ธฐ
# ์ผ์ชฝ ๋
ธ๋์ ์ค๋ฅธ์ชฝ ๋
ธ๋ ๋ฐ๊ฟ์น๊ธฐ
root.left, root.right = root.right, root.left
# ์ผ์ชฝ ์ค๋ฅธ์ชฝ ์์๋
ธ๋๋ค์ ๋ฐ๊ฟ์น๊ธฐ ์๋ฃํ ๋ถ๋ชจ๋
ธ๋ ๋ฐํํ๊ธฐ
return root
# ์ต์ข
๋
ธ๋ ๋ฐ๊ฟ์น๊ธฐ ๋ ํธ๋ฆฌ ๋ฐํํ๊ธฐ
return dfs(root)