236. Lowest Common Ancestor of a Binary Tree

236 Lowest Common Ancestor of a Binary Tree

Total Accepted: 46265 Total Submissions: 160631 Difficulty: Medium
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has 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 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Hide Company Tags Amazon LinkedIn Apple Facebook Microsoft
Hide Tags Tree
Hide Similar Problems (E) Lowest Common Ancestor of a Binary Search Tree


package tree;

public class LowestCommonAncestor {
 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  
  /* https://leetcode.com/discuss/45399/my-java-solution-which-is-easy-to-understand
   *     ___ 1_____
   *   /           \
   *  __2 ___       __ 3 ___
   * /    \     /        \
   * 4        5    6        7
   */

  // p, q in the same subtree, q is the child of p,  e.g  (p,q) is (2, 5) or (3, 7)
  if (root == null || root == p || root == q)  {  
   return root;
  }
  TreeNode left = lowestCommonAncestor(root.left, p, q);
  TreeNode right = lowestCommonAncestor(root.right, p, q);
  
  if (left != null && right != null)  {
   return root;   // p, q are in the different subtree of root  e.g. (p,q) is (4, 6)
  }
  return left != null ? left : right;
  
 }

 public TreeNode dfs_failed(TreeNode root, TreeNode p, TreeNode q) {
  
  TreeNode node = root;

  if (node == null)
   return null;

  if (node == p || node == q) {
   return node;
  }

  if (node.left != null) {

   node = dfs_failed(node.left, p, q);
  }
  if (node.right != null) {
   node = dfs_failed(node.right, p, q);
  }

  return node;

 }

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int[] inorder = { 4, 2, 5, 1, 6, 3, 7 };
  int[] preorder = { 1, 2, 4, 5, 3, 6, 7 };
  int[] output = { 1, 2, 3, 4, 5, 6, 7 };
  ConstructBinaryTreeFromArray cbt = new ConstructBinaryTreeFromArray();
  TreeNode root = cbt.buildTree(inorder, preorder);
   
  LowestCommonAncestor lca = new LowestCommonAncestor();
  TreeNode commonAncesor = lca.lowestCommonAncestor(root, root.left , root.left.right);  // (p,q) = (2, 5)
  
  String res = commonAncesor == null ?  "Null" : String.valueOf(commonAncesor.val);  // 2
   System.out.println(res);
 }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末田盈,一起剝皮案震驚了整個(gè)濱河市进胯,隨后出現(xiàn)的幾起案子丘喻,更是在濱河造成了極大的恐慌叛甫,老刑警劉巖锚扎,帶你破解...
    沈念sama閱讀 222,946評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異福青,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)而咆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,336評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)齐苛,“玉大人翘盖,你說(shuō)我怎么就攤上這事“挤洌” “怎么了馍驯?”我有些...
    開封第一講書人閱讀 169,716評(píng)論 0 364
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)玛痊。 經(jīng)常有香客問我汰瘫,道長(zhǎng),這世上最難降的妖魔是什么擂煞? 我笑而不...
    開封第一講書人閱讀 60,222評(píng)論 1 300
  • 正文 為了忘掉前任混弥,我火速辦了婚禮,結(jié)果婚禮上对省,老公的妹妹穿的比我還像新娘蝗拿。我一直安慰自己,他們只是感情好蒿涎,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,223評(píng)論 6 398
  • 文/花漫 我一把揭開白布哀托。 她就那樣靜靜地躺著,像睡著了一般劳秋。 火紅的嫁衣襯著肌膚如雪仓手。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,807評(píng)論 1 314
  • 那天玻淑,我揣著相機(jī)與錄音嗽冒,去河邊找鬼。 笑死补履,一個(gè)胖子當(dāng)著我的面吹牛添坊,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播箫锤,決...
    沈念sama閱讀 41,235評(píng)論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼帅腌,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了麻汰?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,189評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤戚篙,失蹤者是張志新(化名)和其女友劉穎五鲫,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體岔擂,經(jīng)...
    沈念sama閱讀 46,712評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡位喂,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,775評(píng)論 3 343
  • 正文 我和宋清朗相戀三年浪耘,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片塑崖。...
    茶點(diǎn)故事閱讀 40,926評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡七冲,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出规婆,到底是詐尸還是另有隱情澜躺,我是刑警寧澤,帶...
    沈念sama閱讀 36,580評(píng)論 5 351
  • 正文 年R本政府宣布抒蚜,位于F島的核電站掘鄙,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏嗡髓。R本人自食惡果不足惜操漠,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,259評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望饿这。 院中可真熱鬧浊伙,春花似錦、人聲如沸长捧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,750評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)唆姐。三九已至拗慨,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間奉芦,已是汗流浹背赵抢。 一陣腳步聲響...
    開封第一講書人閱讀 33,867評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留声功,地道東北人烦却。 一個(gè)月前我還...
    沈念sama閱讀 49,368評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像先巴,于是被迫代替她去往敵國(guó)和親其爵。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,930評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容