LCA of Binary Tree Issue

匿名 (未验证) 提交于 2019-12-03 01:19:01

问题:

I have written a code for finding least common ancestor of nodes in binary tree but it seems to return null instead of the LCA.

My algorithm is as below.

  1. Recursively find the ancestor in left and right branch of tree
  2. A node where left as well as right tree has matching elements in the LCA.

    public class LCA {   public static BinaryTreeNode findLCA( BinaryTreeNode root, BinaryTreeNode node1 , BinaryTreeNode node2) {       if (root == null) {     return null; }         BinaryTreeNode left = root.getLeft(); BinaryTreeNode right = root.getRight();   if (left != null && (left == node1 || left == node2)) {     return root;                 }  if (right != null && (right == node1 || right == node2)) {     return root;                 }  if (( findLCA(left, node1, node2) != null) && (findLCA(right, node1, node2) != null)) {              return root; }  return null; }} 

What could be the problem with this code?

回答1:

I think I am able to fix it. I added another condition to see if my recursive findLCA is returning something. If so I return the same value further which fixed the issue. Plz provide your comments if this design is ok.

public static BinaryTreeNode findLCA( BinaryTreeNode root, BinaryTreeNode node1 , BinaryTreeNode node2) {             if (root == null) {         return null;     }             BinaryTreeNode left = root.getLeft();     BinaryTreeNode right = root.getRight();     BinaryTreeNode lcaNode1;     BinaryTreeNode lcaNode2;      if (left != null && (left == node1 || left == node2)) {         return root;                     }      if (right != null && (right == node1 || right == node2)) {         return root;                     }     lcaNode1 =  findLCA(left, node1, node2);     lcaNode2 =  findLCA(right, node1, node2);      if (( lcaNode1 != null) && lcaNode2 != null) {                   return root;     }      if (lcaNode1 != null) {         return lcaNode1;     }      if (lcaNode2 != null) {         return lcaNode2;     }             return null;         } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!