题意:求一个BST中某两个节点LCA….
思路:卧槽。。。竟然求LCA…直接想到的显然是Tarjan的方法或者。。。RMQ+DFS。。。但是感觉。。。leetcode怎么可能考算法。。。。于是想到。。。可以从BST下手。。。
两个节点的LCA的值一定在这两个节点之间。
可以根据这个条件做二分。。。
这道题的收获是。。。不要被已知的东西限制住思路。。。tarjan或者RMQ+DFS显然也能做。。。但是那样的相当于没有用到BST的条件。。。
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 31 32 33 34 |
/** * 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 * Find(TreeNode* root,TreeNode* p,TreeNode *q) { if (root==NULL) return NULL; //实际上这应该不可能发生》。。。 int rt = root->val; int a = p->val; int b = q->val; if (a<=rt&&rt<=b) return root; if (b<=rt&&rt<=a) return root; if (a<rt&&b<rt) return Find(root->left,p,q); if (a>rt&&b>rt) return Find(root->right,p,q); } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root==NULL) return NULL; TreeNode* res = Find(root,p,q); return res; } }; |
说点什么
您将是第一位评论人!