파비의 매일매일 공부기록

2023.04.19 Today's Challenge 본문

Problem Solving/LeetCode

2023.04.19 Today's Challenge

fabichoi 2023. 4. 19. 23:45

https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/

 

Longest ZigZag Path in a Binary Tree - LeetCode

Can you solve this real interview question? Longest ZigZag Path in a Binary Tree - You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: * Choose any node in the binary tree and a direction (right or left). * If the

leetcode.com

DFS소 푸는 문제. 또 트리 나옴 ㅋㅋㅋㅋ

class Solution:
    def longestZigZag(self, root: Optional[TreeNode]) -> int:
        self.pl = 0

        def dfs(node, gl, steps):
            if node:
                self.pl = max(self.pl, steps)
                if gl:
                    dfs(node.left, False, steps+1)
                    dfs(node.right, True, 1)
                else:
                    dfs(node.left, False, 1)
                    dfs(node.right, True, steps + 1)
        
        dfs(root, False, 0)
        dfs(root, True, 0)
        return self.pl
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.04.21 Today's Challenge  (0) 2023.04.21
2023.04.20 Today's Challenge  (0) 2023.04.20
2023.04.18 Today's Challenge  (0) 2023.04.18
2023.04.17 Today's Challenge  (0) 2023.04.17
2023.04.16 Today's Challenge  (0) 2023.04.16
Comments