传送门 nowcoder leetcode
题目描述 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
C++ 代码 - nowcoder 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Solution {public : int lowestCommonAncestor (TreeNode* root, int p, int q) { vector<int > path_p = getPath (root, p); vector<int > path_q = getPath (root, q); int res = 0 ; for (int i = 0 ; i < path_p.size () && i < path_q.size (); i ++) { if (path_p[i] == path_q[i]) res = path_p[i]; else break ; } return res; } vector<int > getPath (TreeNode* root, int target) { vector<int > path; TreeNode* node = root; while (node->val != target) { path.push_back (node->val); if (target < node->val) node = node->left; else node = node->right; } path.push_back (node->val); return path; } };
C++ 代码 - leetcode 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Solution {public : TreeNode* lowestCommonAncestor (TreeNode* root, TreeNode* p, TreeNode* q) { return find (root, p->val, q->val); } TreeNode* find (TreeNode* root, int val1, int val2) { if (!root) return nullptr ; if (root->val == val1 || root->val == val2) { return root; } TreeNode* left = find (root->left, val1, val2); TreeNode* right = find (root->right, val1, val2); if (left && right) { return root; } return left ? left : right; } };