easy235. Lowest Common Ancestor of a Binary Search Tree

Posted Sherry_Yang

tags:

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

题意大概是,找两个节点的最低公共祖先

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == NULL)
            return NULL;
        if (root->val > p->val && root->val > q->val)   
            return lowestCommonAncestor(root->left,p,q);
        if (root->val < p->val && root->val < q->val)
            return lowestCommonAncestor(root->right,p,q);
        return root;   //出现了一大一小,就可以返回root了
    }
};

 

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

Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]

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

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