993_Cousins in Binary Tree

less than 1 minute read

https://leetcode.com/problems/cousins-in-binary-tree/

binary tree를 순회하면서
dictionary에 해당 노드의 depth와 parent node를 표시해주었다.

그 뒤 x,y값의 깊이가 같은지 확인하고 부모노드가 같은지 확인하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution(object):
    def isCousins(self, root, x, y):
        """
        :type root: TreeNode
        :type x: int
        :type y: int
        :rtype: bool
        """
        dictionary = {}
        dictionary[root.val] = (0, root)
        def preorderTraverse(root, depth):
            
            if root:
                #print(root.val)
                if root.left:
                    dictionary[root.left.val] = (depth, root)
                if root.right:
                    dictionary[root.right.val] = (depth, root)
                
                
                preorderTraverse(root.left, depth+1)                
                preorderTraverse(root.right, depth+1)
        
        
        preorderTraverse(root, 1)
        
        if dictionary[x][0] == dictionary[y][0] and dictionary[x][1] != dictionary[y][1]:
            return True
        
        else:
            return False