You are viewing a single comment's thread. Return to all comments →
this is C# solotion
using System; // Technology stack and framework: .NET public class Node { public int info; public Node left; public Node right; public int level; public Node(int info) { this.info = info; this.left = null; this.right = null; this.level = 0; } public override string ToString() { return info.ToString(); } } public class BinarySearchTree { public Node root; public void create(int val) { if (root == null) { root = new Node(val); } else { Node current = root; while (true) { if (val < current.info) { if (current.left != null) { current = current.left; } else { current.left = new Node(val); break; } } else if (val > current.info) { if (current.right != null) { current = current.right; } else { current.right = new Node(val); break; } } else { break; } } } } } public class MainClass { public static Node lca(Node root, int v1, int v2) { Node current = root; while (true) { if ((current.info < v1) && (current.info < v2) && (current.right != null)) { current = current.right; } else if ((current.info > v1) && (current.info > v2) && (current.left != null)) { current = current.left; } else { return current; } } } public static void Main() { BinarySearchTree tree = new BinarySearchTree(); int t = Convert.ToInt32(Console.ReadLine()); int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse); for (int i = 0; i < t; i++) { tree.create(arr[i]); } int[] v = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse); Node ans = lca(tree.root, v[0], v[1]); Console.WriteLine(ans.info); } }
Seems like cookies are disabled on this browser, please enable them to open this website
Binary Search Tree : Lowest Common Ancestor
You are viewing a single comment's thread. Return to all comments →
this is C# solotion