Given A binary search tree (BST), find the lowest common ancestor (LCA) of the Given nodes in the BST.
According to the definition of the LCA in Wikipedia: "The lowest common ancestor is defined between," nodes V and W as the L Owest node in T, have both V and W as descendants (where we allow a node to be a descendant of itself). "
_______6______ / ___2__ ___8__ / \ / 0 _4 7 9 / 3 5
For example, the lowest common ancestor (LCA) of nodes and are 2
8
6
. Another example is LCA of nodes 2
4
2
and are, since a node can be a descendant of itself according to the L CA definition.
Subscribe to see which companies asked this question
Hide TagsTreeHide Similar Problems(M) Lowest Common Ancestor of a Binary Tree
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) {intMin =math.min (P.val,q.val); intMax =Math.max (P.val,q.val); while(root!=NULL) { if(min <= root.val && Max >=root.val)returnRoot; if(Min > Root.val && max >root.val) Root=Root.right; if(Min < root.val && Max <root.val) Root=Root.left; } returnRoot; }}
236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of the Given nodes in the tree.
According to the definition of the LCA in Wikipedia: "The lowest common ancestor is defined between," nodes V and W as the L Owest node in T, have both V and W as descendants (where we allow a node to be a descendant of itself). "
_______3______ / ___5__ ___1__ / \ / 6 _2 0 8 / 7 4
For example, the lowest common ancestor (LCA) of nodes and are 5
1
3
. Another example is LCA of nodes 5
4
5
and are, since a node can be a descendant of itself according to the L CA definition.
Subscribe to see which companies asked this question
235. Lowest Common Ancestor of a Binary Search Tree && 236. Lowest Common Ancestor of a Binary Tree