zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    spark实验四(2)
    spark实验四
    神奇的一天
    Spark实验三
    Scala实验任务三
    Scala实验任务二
    Scala语言实验任务一
    kettle的基本使用
    质量属性之安全性战术
    datax相关
  • 原文地址:https://www.cnblogs.com/aguai1992/p/5351895.html
Copyright © 2011-2022 走看看