leetcode+ BST中两个节点的最近公共祖先,递归,要使用中序有序的属性

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/

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->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;
    }
};

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/81121344