[leetcode #993] Cousins in Binary Tree

Seongyeol Shin·2021년 10월 18일
0

leetcode

목록 보기
52/196
post-thumbnail

Problem

Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.

Two nodes of a binary tree are cousins if they have the same depth with different parents.

Note that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.

Example 1:

Input: root = [1,2,3,4], x = 4, y = 3
Output: false

Example 2:

Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true

Example 3:

Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false

Constraints:

・ The number of nodes in the tree is in the range [2, 100].
・ 1 <= Node.val <= 100
・ Each node has a unique value.
・ x != y
・ x and y are exist in the tree.

Idea

Binary Tree의 두 노드를 주고 노드의 관계가 cousin인지 확인하는 문제다. Cousin은 부모가 서로 다르고 depth가 같은 노드를 말한다. Depth가 같고 부모가 같으면 sibling 노드라 해야 맞을 것이다.

두 노드의 depth를 저장하는 것이 번거로워 class의 멤버 변수를 활용했다. 또한 부모 노드가 같은지도 확인하기 위해 변수를 추가했다. Tree 탐색은 recursive 함수를 이용했으며, 해당 노드의 값이 x 또는 y와 같다면 노드의 depth와 부모의 값을 기록해 둔다. 무의미한 탐색을 끝내기 위해 depth가 모두 설정이 되었으면 재귀함수를 끝낸다.

Binary Tree 탐색이 끝났으면 두 노드의 depth와 두 노드의 부모 값을 비교해 결과를 리턴한다.

Solution

class Solution {
    int depthX = 0;
    int depthY = 0;
    int parentX = 0;
    int parentY = 0;

    public boolean isCousins(TreeNode root, int x, int y) {
    	traverseTree(root, x, y, root.val, 0);

        return depthX == depthY && parentX != parentY;
    }

    private void traverseTree(TreeNode node, int x, int y, int parent, int depth) {
        if (node == null)
            return;

        if (node.val == x) {
            depthX = depth;
            parentX = parent;
        } else if (node.val == y) {
            depthY = depth;
            parentY = parent;
        }

        if (depthX != 0 && depthY != 0)
            return;

        traverseTree(node.left, x, y, node.val, depth+1);
        traverseTree(node.right, x, y, node.val, depth+1);
    }
}

Reference

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

profile
서버개발자 토모입니다

0개의 댓글