235. Lowest Common Ancestor of a Binary Search Tree

Posted 阿怪123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了235. Lowest Common Ancestor of a Binary Search Tree相关的知识,希望对你有一定的参考价值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //主要分为几种情况
        //1 如果p或者q有一个直接与root相等,则直接返回root即可
        //2 如果p q都不等于root,则进行下一步判断,如果都在左子树当中,则堆左子树进行递归
        //3 如果都在右子树当中,则对右子树进行递归
        //4 如果一个在左子树,一个在右子树当中,则当前root就是结果,直接返回即可。
        
        TreeNode temp=root;
        
        if(root==p||root==q)
        {
            return temp;
        }
        else
        {
            if(isIn(temp.left,p)&&isIn(temp.left,q))
            {
                return lowestCommonAncestor(temp.left,p,q);
            }
            else if(isIn(temp.right,p)&&isIn(temp.right,q))
            {
                return lowestCommonAncestor(temp.right,p,q);
            }
            else
                return temp;
        }
        
        
        
    }
    public boolean isIn(TreeNode root,TreeNode target)
    {
        boolean res=false;
        if(target==root)
            return true;
        else
        {
            if(root.left!=null)
                res=isIn(root.left,target);
            if(root.right!=null&&res==false)
                res=isIn(root.right,target);
        }
        return res;
    }
}

 

以上是关于235. Lowest Common Ancestor of a Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

LC.235.Lowest Common Ancestor of a Binary Search Tree

LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Searc

#Leetcode# 235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree