zoukankan      html  css  js  c++  java
  • 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);
    
        }
    };
    自己选择的路,跪着也要走完。朋友们,虽然这个世界日益浮躁起来,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。
  • 相关阅读:
    NodeJS学习笔记之Connect中间件模块(一)
    XML CDATA节点
    6个强大的AngularJS扩展应用
    java使用poi读取ppt文件和poi读取excel、word示例
    Java log4j详细教程
    JAVA8 十大新特性详解
    Express 路由
    基于 Node.js 平台,快速、开放、极简的 web 开发框架。
    Node.js 手册查询-1-核心模块方法
    Node.js 手册查询-2-MongoDB数据库方法
  • 原文地址:https://www.cnblogs.com/WTSRUVF/p/15501421.html
Copyright © 2011-2022 走看看