We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b56d702 commit 0e1484dCopy full SHA for 0e1484d
lowest-common-ancestor-of-a-binary-search-tree/jaejeong1.java
@@ -0,0 +1,33 @@
1
+
2
+// Definition for a binary tree node.
3
+class TreeNode {
4
+ int val;
5
+ TreeNode left;
6
+ TreeNode right;
7
8
+ TreeNode(int x) {
9
+ val = x;
10
+ }
11
+}
12
13
14
+class Solution {
15
+ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
16
+ // 플이: p,q 둘다 root 보다 값이 적으면 왼쪽 서브트리를, 둘다 크면 오른쪽 서브트리를 탐색해야한다.
17
+ // 그렇지 않으면 해당 root가 최저 공통 조상이 된다.
18
+ // TC: O(H), H: 트리의 높이
19
+ // SC: O(1)
20
+ var node = root;
21
+ while (node != null) {
22
+ if (p.val < node.val && q.val < node.val) {
23
+ node = node.left;
24
+ } else if (p.val > node.val && q.val > node.val) {
25
+ node = node.right;
26
+ } else {
27
+ break;
28
29
30
31
+ return node;
32
33
0 commit comments