We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Loading...
  • Practice
  • Compete
  • Jobs
  • Leaderboard
  1. Practice
  2. Data Structures
  3. Trees
  4. Binary Search Tree : Lowest Common Ancestor
  5. Discussions

Binary Search Tree : Lowest Common Ancestor

  • Problem
  • Submissions
  • Leaderboard
  • Discussions
  • Editorial

    You are viewing a single comment's thread. Return to all comments →

  • maverick55 3 years ago+ 2 comments

    couldn't think of a more perfect solution than this one.

    0|
    ParentPermalink
    • RaviShekhar93 2 years ago+ 0 comments

      That is because, its the same as the code in Editorial Section

      3|
      ParentPermalink
    • b0kater 2 years ago+ 6 comments

      I prefer an iterative solution to this problem rather than recursive. The code is similarly brief, and there isn't any need to load up the call stack.

      static Node lca(Node root,int v1,int v2)
      {
          Node temp = root; // not necessary, just use root, just a leftover from a different attempt.
          
          while (true) {
              if (temp.data > v1 && temp.data > v2) {
                  temp = temp.left;
              } else if (temp.data < v1 && temp.data < v2) {
                  temp = temp.right;
              } else {
                  return temp;
              }
          }
      }
      
      21|
      ParentPermalink
      • bennattj 1 year ago+ 0 comments

        I agree. Especially considering that this is clearly tail-recursive (which makes it trivial to convert to an iterative solution).

        0|
        ParentPermalink
      • Mohit_Yadav_389 12 months ago+ 0 comments

        I came with exact this solution!

        1|
        ParentPermalink
      • jaskaransingh_17 11 months ago+ 0 comments

        awesome solution:)

        0|
        ParentPermalink
      • anujpriyadarshi 9 months ago+ 0 comments

        This code gives the output as 1 and result is correct. In an another code output is 4 and then too result is correct.

        0|
        ParentPermalink
      • Arun_Raj7 2 months ago+ 0 comments

        Elegant and simplistic solution. wow.

        1|
        ParentPermalink
      • chesschingis 1 month ago+ 0 comments

        I vastly prefer this version! Simplicity and elegance.

        0|
        ParentPermalink
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature