[力扣题解] 236. 二叉树的最近公共祖先

题目:236. 二叉树的最近公共祖先

思路

代码

用深度搜索的思想(好吧,前序、中序、后序都是深搜思想),保存寻找路径,看看找到2个节点的路径的重合部分,就可以找到最近公共祖先;

/**
 * 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:
    vector<TreeNode*> path;
    vector<vector<TreeNode*>> result;
    void travel(TreeNode* cur, TreeNode* target)
    {   
        if(cur == NULL)
        {
            return;
        }
        // 中
        if(cur->val == target->val)
        {
            result.push_back(path);
            return;
        }
        // 左
        if(cur->left)
        {
            path.push_back(cur->left);
            travel(cur->left, target);
            path.pop_back();
        }
        // 右
        if(cur->right)
        {
            path.push_back(cur->right);
            travel(cur->right, target);
            path.pop_back();
        }
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
    {
        int i, j, min_length;
        path.push_back(root);
        travel(root, q);
        path.clear();
        path.push_back(root);
        
        travel(root, p);
        /*
        for(i = 0; i < result.size(); i++)
        {
            for(j = 0; j < result[i].size(); j++)
            {
                cout << result[i][j]->val << ", ";
            }
            cout << endl;
        }*/
        // cout << "result[0].size() : " << result[0].size() << endl;
        // cout << "result[1].size() : " << result[1].size() << endl;
        min_length = min(result[0].size(), result[1].size());
        for(i = 0; i < min_length; i++)
        {
            if(result[0][i]->val == result[1][i]->val)
            {
                continue;
            }
            else
            {
                break;
            }
        }
        // cout << "i : " << i << "result[0][i] : " << result[0][i]->val;
        return result[0][i-1];
    }
};

相关推荐

  1. [题解] 236. 最近公共祖先

    2024-06-11 05:46:01       9 阅读
  2. 刷题练习】236. 最近公共祖先

    2024-06-11 05:46:01       34 阅读
  3. 236. 最近公共祖先

    2024-06-11 05:46:01       28 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-11 05:46:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-11 05:46:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-11 05:46:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-11 05:46:01       18 阅读

热门阅读

  1. vue manually select

    2024-06-11 05:46:01       7 阅读
  2. 初始化css

    2024-06-11 05:46:01       7 阅读
  3. VM渗透系统合集(下载链接)

    2024-06-11 05:46:01       10 阅读
  4. springboot事件发布机制之生产运用

    2024-06-11 05:46:01       8 阅读
  5. C++ C_style string overview and basic Input funcitons

    2024-06-11 05:46:01       5 阅读
  6. Helm在线部署Longhorn(1.6.0版本)分布式存储

    2024-06-11 05:46:01       7 阅读