lca算法思路总结:
思想:二叉查找树的性质,如果是祖先,和左右子树的差值乘积为负数。
如果在左边,往左边进行递归。如果往右边,往右边递归。
/** * 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: TreeNode* ans = NULL; TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { lca(root, p , q); return ans; } void lca(TreeNode* root, TreeNode* p, TreeNode* q) { if((root->val - p->val) * (root->val - q->val) <= 0) ans = root; else if(root->val < p->val && root->val < q->val) lca(root->right, p, q); else lca(root->left, p ,q); } };