Tag Archives: lca

Find LCA in Binary Tree, Find LCA in BST

I wrote finding lca long time ago. Today, I learned this more concise code for finding LCA in Binary Tree. The idea is that if there is no p or q in bottom, return null. Or return p, q or root. public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == p… Read More »

find lca(lowest common ancestry) in a binary tree

public static Tree findLca(Tree tree, MyInteger lcaNum, int node1, int node2){ if(tree==null){ return null; } MyInteger lLca = new MyInteger(0); Tree ltree = findLca(tree.left, lLca, node1, node2); if(lLca.i==2){ lcaNum.i=2; return ltree; } MyInteger rLca = new MyInteger(0); Tree rtree = findLca(tree.right, rLca, node1, node2); if(rLca.i==2){ lcaNum.i=2; return rtree; } int selfLca = 0; if(node1==tree.value||node2==tree.value){ selfLca… Read More »