首页 > 其他 > 详细

Lowest Common Ancestor of a Binary Search Tree

时间:2015-12-04 23:00:26      阅读:407      评论:0      收藏:0      [点我收藏+]

题目连接

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!