1. 程式人生 > 其它 >1123. 最深葉節點的最近公共祖先

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); } };
自己選擇的路,跪著也要走完。朋友們,雖然這個世界日益浮躁起來,只要能夠為了當時純粹的夢想和感動堅持努力下去,不管其它人怎麼樣,我們也能夠保持自己的本色走下去。