You are viewing a single comment's thread. Return to all comments →
Solution with commented explanation.
public static Node lca(Node root, int v1, int v2) { // Write your code here. return recLca(root, v1, v2); } public static Node recLca(Node root, int v1, int v2) { if (root == null) { return null; } if (root.data == v1 || root.data == v2) { return root; } Node leftFind = recLca(root.left, v1, v2); Node rightFind = recLca(root.right, v1, v2); if (leftFind == null || rightFind == null) { return leftFind == null ? rightFind : leftFind; } if (leftFind.data == rightFind.data) { return leftFind; } else{ return root; } }
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 →
Solution with commented explanation.
public static Node lca(Node root, int v1, int v2) { // Write your code here. return recLca(root, v1, v2); } public static Node recLca(Node root, int v1, int v2) { if (root == null) { return null; } if (root.data == v1 || root.data == v2) { return root; } Node leftFind = recLca(root.left, v1, v2); Node rightFind = recLca(root.right, v1, v2); if (leftFind == null || rightFind == null) { return leftFind == null ? rightFind : leftFind; } if (leftFind.data == rightFind.data) { return leftFind; } else{ return root; } }