Simple while loop java solution


  • 5
    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            boolean change=true;
            while(change){       //when p and q on the two side of BST (or one is equal to root), exit the loop
                change=false;
                while(p.val<root.val&&q.val<root.val){
                    root=root.left;
                    change=true;
                }
                
                while(p.val>root.val&&q.val>root.val){
                    root=root.right;
                    change=true;
                }
            }
            
            
            return root;
            
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.