1123. 最深叶节点的最近公共祖先

就找出最后一层的所有节点,依次求lca就行

lca暴力就行

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int height;
    int idx[1010];
    int pre[1010];
    vector<TreeNode*> v;
    void dfs1(TreeNode* root, int h, int f)
    {
        if(root == nullptr)
            return;
        height = max(height, h);
        idx[root->val] = h;
        pre[root->val] = f;
        dfs1(root->left, h + 1, root->val);
        dfs1(root->right, h + 1, root->val);
    }
    void dfs2(TreeNode* root, int h)
    {
        if(root == nullptr) return;
        if(h == height)
        {
            v.push_back(root);
        }

        dfs2(root->left, h + 1);
        dfs2(root->right, h + 1);
    }
    int query(int x, int y)
    {
        
        int f1 = idx[x], f2 = idx[y];
        while(x != y)
        {
            while(x != y && f1 >= f2)
            {
                x = pre[x];
                f1 = idx[x];
            }
            while(x != y && f1 <= f2)
            {
                y = pre[y];
                f2 = idx[y];
            }
        }

        return x;
    }
    TreeNode* dfs3(TreeNode* root, int x)
    {
        if(root == nullptr) return nullptr;
        if(root->val == x)
            return root;
        TreeNode* r1 = dfs3(root->left, x);
        if(r1) return r1;
        TreeNode* r2 = dfs3(root->right, x);
        if(r2) return r2;
        return nullptr;
    }

    TreeNode* lcaDeepestLeaves(TreeNode* root) {
        height = 0;
        dfs1(root, 0, -1);
        dfs2(root, 0);
        int len = v.size();
        int x = v[0]->val, y;
        for(int i = 1; i < len; i++)
        {
            y = v[i]->val;
            x = query(x, y);
        }
        return dfs3(root, x);

    }
};
自己选择的路,跪着也要走完。朋友们,虽然这个世界日益浮躁起来,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。
原文地址:https://www.cnblogs.com/WTSRUVF/p/15501421.html