(Leet Code c++)Lowest Common Ancestor of a Binary Search Tree

(Leet Code c++)Lowest Common Ancestor of a Binary Search Tree

728x90

반응형

235. Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [2,1], p = 2, q = 1 Output: 2

Constraints:

The number of nodes in the tree is in the range [2, 105].

[2, 105]. -109 <= Node.val <= 109

<= Node.val <= 109 All Node.val are unique .

Node.val are . p != q

p and q will exist in the BST.

728x90

이진 트리의 최소 공통 부모를 찾는 문제.

백준 알고리즘의 11437 LCA와 같은 문제다.

https://eunchanee.tistory.com/267

다만 이 문제의 차이점은 int형이 아닌 TreeNode * 을 리턴해야 하기 때문에,

map을 활용했다.

(노드에 담겨있는 수의 범위가 다르기 때문에)

또한, 노드에 담겨있는 값이 유니크하기 때문에 visited는 없어도 된다.

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: map parent; map depth; void dfs(TreeNode * node, int dpt){ visited[node->val] = true; depth[node->val] = dpt; if(node->left != NULL){ parent[node->left->val] = node; dfs(node->left, dpt + 1); } if(node->right != NULL){ parent[node->right->val] = node; dfs(node->right, dpt + 1); } } TreeNode * lca(TreeNode * p, TreeNode * q){ while(depth[p->val] != depth[q->val]){ if(depth[p->val] > depth[q->val]){ p = parent[p->val]; } else{ q = parent[q->val]; } } while(p->val != q->val){ p = parent[p->val]; q = parent[q->val]; } return p; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode * answer; if(root != NULL){ dfs(root, 0); answer = lca(p, q); } return answer; } };

728x90

반응형

from http://eunchanee.tistory.com/515 by ccl(A) rewrite - 2021-07-28 11:00:20