-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLowest Common Ancestor of a Binary Search Tree
More file actions
33 lines (28 loc) · 1.27 KB
/
Copy pathLowest Common Ancestor of a Binary Search Tree
File metadata and controls
33 lines (28 loc) · 1.27 KB
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
32
33
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).”
Solution - c#:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null)return null;
if(IsFirstParentSecond(p,q))return p;
if(IsFirstParentSecond(q,p))return q;
if((p.val<=root.val && q.val>=root.val) || (q.val<=root.val && p.val>=root.val))return root;
if(p.val>root.val)return LowestCommonAncestor(root.right,p,q);
else return LowestCommonAncestor(root.left,p,q);
}
public bool IsFirstParentSecond(TreeNode first,TreeNode second)
{
if((first.left!=null && first.left==second) ||(first.right!=null && first.right==second))return true;
return false;
}
}