欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

235. Lowest Common Ancestor of a Binary Search Tree

程序员文章站 2022-07-14 14:13:51
...

235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree


LeetCode里关于树的题似乎很多都用递归做比较好,这道题用常规方法比较麻烦,但是用递归就很简洁(看了答案才醒悟……)

递归解法如***意题中给出的是BST,左子节点的键值<根节点的键值<右子节点的键值):

/**
 * 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 (p->val<root->val && q->val<root->val) return lowestCommonAncestor(root->left, p, q);
        else if (p->val>root->val && q->val>root->val) return lowestCommonAncestor(root->right, p, q);
        else return root;
    }
};