剑指--找出两个二叉树节点的最小父节点

这篇博客介绍了两种在二叉树中寻找两个节点最近公共祖先的算法。方法一是通过路径记录,时间复杂度为O(n),空间复杂度也为O(n);方法二是采用递归的方式,时间复杂度为O(n),空间复杂度为O(logn)。这两种方法都在寻找过程中避免了回溯,提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法1:

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    void push_vec(TreeNode* root, int o1, 
                  vector<int>& path1, 
                  bool& find1) {
        if (root == nullptr || (find1)) {
            return;
        }
        if (!find1 && root->val == o1) {
            path1.push_back(root->val);
            find1 = true;
            return;
        }
             
        if (!find1 && root->left) {
            path1.push_back(root->val);
            push_vec(root->left, o1, path1, find1);
            if(!find1) {
                path1.pop_back();
            }
        }
         if (!find1 && root->right) {
            path1.push_back(root->val);
            push_vec(root->right, o1, path1, find1);
            if(!find1) {
                path1.pop_back();
            }
        }
    }
    int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
        // write code here
        bool find1 = false;
        bool find2 = false;
        vector<int> path1;
        vector<int> path2;
        push_vec(root, o1, path1, find1);
        push_vec(root, o2, path2, find2);
        int i,j;
        for (i = 0, j = 0; i < path1.size() && j < path2.size();
            i++, j++) {
            if (path1[i] != path2[j])
                break;
        }
        return path1[i-1];
    }
};

在这里插入图片描述

时间复杂度2O(n)和空间复杂度2O(n)都高,

方法2

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    TreeNode* find(TreeNode* root, int o1, int o2) {
        if (!root || root->val == o1 || root->val == o2) {
            return root;
        }
        TreeNode* left = find(root->left, o1, o2);
        if (left == nullptr) {
            return find(root->right, o1, o2);
        }
        TreeNode* right = find(root->right, o1, o2);
        if (right == nullptr) {
            return left;
        }
        return root;
    }
    int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
        // write code here
        return find(root, o1, o2)->val;
    }
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值