235. 二叉搜索树的最近公共祖先
/** * 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(!root||root==p||root==q) return root; if(p->val<root->val&&q->val<root->val) return lowestCommonAncestor(root->left, p, q); if(p->val>root->val&&q->val>root->val) return lowestCommonAncestor(root->right,p,q); return root; } };
思路:迭代法
/** * 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode *node = root; while(node) { if(p->val>node->val&&q->val>node->val) node = node->right; else if(p->val<node->val&&q->val<node->val) node = node->left; else break; } return node; } };
原文:https://www.cnblogs.com/jessica216/p/13520289.html