๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿงฉ Algorithm/DFS BFS

[LeetCode] 226๋ฒˆ: Invert Binary Tree

by HelloRabbit 2023. 3. 10.
728x90

Hint

1. DFS ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์‚ฌ์šฉํ•ด์•ผํ•จ
2. ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ์— ์ž์‹ ๋…ธ๋“œ๊ฐ€ ์žˆ๋‹ค๋ฉด ๋ฐ”๊ฟ”์น˜๊ธฐ ํ•ด์ฃผ๋ฉด ๋จ

DFS ์ˆœ์„œ๋„

 

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)

 

 

 

'๐Ÿงฉ Algorithm > DFS BFS' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode] 2236๋ฒˆ: ํŠธ๋ฆฌ ๊ตฌ์กฐ  (0) 2023.03.09

๋Œ“๊ธ€