题解 | #二叉搜索树的最近公共祖先#

二叉搜索树的最近公共祖先

http://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param p int整型 
     * @param q int整型 
     * @return int整型
     */
    int lowestCommonAncestor(TreeNode* root, int p, int q) {
        // write code here
        if (root->val > p && root->val > q) return lowestCommonAncestor(root->left, p, q);
        if (root->val < p && root->val < q) return lowestCommonAncestor(root->right, p, q);
        return root->val;
    }
};
全部评论

相关推荐

10-09 17:17
已编辑
门头沟学院 Java
活泼的代码渣渣在泡池...:同学你好,我也是学院本,后天要面这个亚信科技,是实习,请问问题都啥样呀,我项目就做了网上的,这是第一次面试
投递多益网络等公司10个岗位
点赞 评论 收藏
分享
08-21 10:11
已编辑
南京邮电大学 Java
Java后端劝退第一...:我mentor也人很好,感觉就是同龄人,昨天出去散步看他摘了根狗尾巴草一直转,特别搞笑
你被mentor骂过吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务