LeetCode 235. Lowest Common Ancestor of a Binary Search Tree

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

思路

从root到p q分别有一条路径,两条路径从root开始重合,要找到LCA,即找到最后一个重合的结点,找到分叉点。对于路径中处于分叉点以上的任意结点n,p q必然在n的同一个子树中,再加上BST的性质,即可找到分叉点。题目告知所有结点值不同,且p q一定存在,所以处理比较简单。

代码

/**
 * 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) {
        while(true) {
            if(p->val < root->val && q->val < root->val) { // 同在左子树
                root = root->left;
            } else if(p->val > root->val && q->val > root->val) { // 同在右子树
                root = root->right;
            } else { // root即分叉点,有可能是p q中的一个
                return root;
            }
        }
    }
};

一开始没注意到是BST,用了下面的方法。先遍历二叉树找到root到p q的路径,保存在两个vector中,找到两路径最后一个相同的结点。

/**
 * 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) {
        vector<TreeNode *> p1, p2;
        find_path(p1, root, p);
        find_path(p2, root, q);
        int i = 0;
        while(i < p1.size() && i < p2.size() && p1[i] == p2[i]) {
            i++;
        }
        return p1[i-1];
    }
private:
    bool find_path(vector<TreeNode *> &path, TreeNode *curr, TreeNode *target) {
        if(!curr) return false;
        path.push_back(curr);
        if(curr == target) {
            return true;
        }
        if(find_path(path, curr->left, target)) return true;
        if(find_path(path, curr->right, target)) return true;
        path.pop_back();
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值