給定一個二叉樹, 找到該樹中兩個指定節點的最近公共祖先。node
百度百科中最近公共祖先的定義爲:「對於有根樹 T 的兩個結點 p、q,最近公共祖先表示爲一個結點 x,知足 x 是 p、q 的祖先且 x 的深度儘量大(一個節點也能夠是它本身的祖先)。」ide
例如,給定以下二叉樹: root = [3,5,1,6,2,0,8,null,null,7,4]
示例 1:code輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
輸出: 3
解釋: 節點 5 和節點 1 的最近公共祖先是節點 3。get
解題思路:先分別記錄根節點到兩個結點的路徑,再求出兩個路徑中最後一個相同的結點即爲最近公共祖先.it
實現代碼io
/** * 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: void path_search(TreeNode *node, int &flag, vector<TreeNode* >&path, vector<TreeNode* > &result, int target) { if(!node || flag) return ; path.push_back(node); if(node->val == target) { flag = 1; result = path; } path_search(node->left, flag, path, result,target); path_search(node->right, flag, path, result, target); path.pop_back(); } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { vector<TreeNode* > path; vector<TreeNode* > path_p; vector<TreeNode* > path_q; int flag = 0; path_search(root, flag, path, path_p, p->val); flag = 0; path.clear(); path_search(root, flag, path, path_q, q->val); int path_length = min(path_p.size(), path_q.size()); TreeNode* result; for(int i = 0; i < path_length; i++) { if(path_p[i] == path_q[i]) result = path_p[i]; } return result; } };