在二叉树中找到两个节点的最近公共祖先

思路:深度遍历以所求节点为终止节点的路径,判断两个路径的交点

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
        // write code here
        vector<int> o1_vec;
        vector<int> o2_vec;
        vector<int> path;
        getPath(root, o1, o1_vec,path,0);
        path.clear();
        getPath(root, o2, o2_vec,path,0);
        int path_len = 0;
        int result = 0;
        if(o1_vec.size()>o2_vec.size()){
            path_len = o1_vec.size();
        }
        else{
            path_len = o2_vec.size();
        }
        for(int i = 0;i<path_len;i++){
            if(o1_vec[i] == o2_vec[i]){
                result = o1_vec[i];
            }
        }
        return result;
    }
private:
    void getPath(TreeNode* node,const int target,vector<int> &res,vector<int> &path,int flag){
        if(node == NULL || flag == 1){
            return ;
        }
        path.push_back(node->val);
        if(node->val == target){
            flag = 1;
            res = path;
        }
        getPath(node->left, target, res,path,flag);
        getPath(node->right, target, res,path,flag);
        path.pop_back();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值