当前位置 博文首页 > Liu,:Leetcode—— 二叉搜索树的最近公共祖先

    Liu,:Leetcode—— 二叉搜索树的最近公共祖先

    作者:[db:作者] 时间:2021-07-20 09:42

    1. 题目

    在这里插入图片描述

    2. 题解

    • 如果p,q分别在根节点两侧,那么根节点就是最近公共祖先
    • 再分别判断p,q在根节点左右两种情况
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    
    class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            TreeNode ancerstor = root;
            while(true){
                if(ancerstor.val > p.val && ancerstor.val > q.val)
                    ancerstor = ancerstor.left;
                else if(ancerstor.val < p.val && ancerstor.val < q.val)
                    ancerstor = ancerstor.right;
                else    
                    break;
            }
            return ancerstor;
        }
    }
    
    
    cs
    下一篇:没有了