leetcode 困难题 耗时100内存100 1483. Kth Ancestor of a Tree Node 树节点的第 K 个祖先
Problem: 1483. Kth Ancestor of a Tree Node 树节点的第 K 个祖先耗时100%内存100%parent列表里面都不是叶子节点用状态数组标记非叶子节点对所有叶子节点用数组tmp记录当前叶子节点到根节点0的路径用tr数组保存tmplist数组记录当前节点在tr的索引在tmp的索引list数组记录了每个节点第一次出现在tr的索引出现在tmp中的索引最后查询的时候从list当中拿到索引{index, ind}若ind k tr[index].size()表示不可能返回-1否则就返回tr[index][ind k]Codeclass TreeAncestor { public: vectorint par, tmp; vectorpairint, int list; vectorvectorint tr; TreeAncestor(int n, vectorint parent) { par std::move(parent); vectorbool status(n, false); list.assign(n, {-1, -1}); for(int i 1; i n; i) status[par[i]] true; int node, sz; for(int i 0; i n; i) { if(status[i]false) { node i; tmp {node}; sz tr.size(); while(node 0) { if(list[node].first 0) list[node] {sz, tmp.size()-1}; node par[node]; tmp.push_back(node); } tr.push_back(tmp); } } } int getKthAncestor(int node, int k) { pairint, int pr list[node]; int index pr.first; int ind pr.second; int sz tr[index].size(); ind ind k; if(ind sz) return -1; return tr[index][ind]; } }; /** * Your TreeAncestor object will be instantiated and called as such: * TreeAncestor* obj new TreeAncestor(n, parent); * int param_1 obj-getKthAncestor(node,k); */
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2447582.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!