https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
同上, 用二叉树的性质要快一些,懒得改了。。
/** * 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 { private: typedef TreeNode* T; typedef vector<T> vec; public: T lowestCommonAncestor(T root, T p, T q) { if (!root || !p || !q) return NULL; A.clear(), B.clear(), C.clear(); dfs(root, p, q, A, B, C); if (B.empty() || C.empty()) return NULL; reverse(B.begin(), B.end()); reverse(C.begin(), C.end()); for (auto &r : B) { vec::iterator it = find(C.begin(), C.end(), r); if (it != C.end()) return r; } return NULL; } private: void dfs(T x, T p, T q, vec &A, vec &B, vec &C) { if (!x) return; A.push_back(x); if (x == p) B = A; if (x == q) C = A; dfs(x->left, p, q, A, B, C); dfs(x->right, p, q, A, B, C); A.pop_back(); } vec A, B, C; };
Lowest Common Ancestor of a Binary Search Tree
原文:http://www.cnblogs.com/GadyPu/p/5020677.html