Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 9. 14. 23:45

https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree

 

Pseudo-Palindromic Paths in a 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

펠린드롬의 체크를 비트 연산 및 쉬프트 연산으로 처리하는게 인상 깊었음. 
근데 왜 난이도가 Medium?

class Solution:
    def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
        count = 0
        stack = [(root, 0)]
        while stack:
            node, path = stack.pop()
            if node is not None:
                path = path ^ (1 << node.val)
                
                if node.left is None and node.right is None:
                    if path & (path - 1) == 0:
                        count += 1
                else:
                    stack.append((node.right, path))
                    stack.append((node.left, path))
        return count
반응형