您的位置:首页 > 其它

leetcode@ [236] Lowest Common Ancestor of a Binary Tree(Tree)

2016-01-03 16:06 267 查看
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

/**
* 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:
void findPath(TreeNode* root, vector<TreeNode* >& load, vector<TreeNode* >& path, TreeNode* p) {
if(root == NULL) return;
if(root == p) {
path = load;
return;
}

load.push_back(root->left);
findPath(root->left, load, path, p);
load.pop_back();

load.push_back(root->right);
findPath(root->right, load, path, p);
load.pop_back();
}
void reverse_vector(vector<TreeNode* > v) {
vector<TreeNode* > res; res.clear();

for(int i=v.size()-1;i>=0;--i) res.push_back(v[i]);
v = res;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(p == q) return p;

vector<TreeNode* > load1, load2, path1, path2;

TreeNode *r = root;
load1.push_back(r);
load2.push_back(r);

findPath(r, load1, path1, p);
findPath(r, load2, path2, q);

reverse_vector(path1);
reverse_vector(path2);

int i = 0, j = 0, m = path1.size(), n = path2.size(), resi;
cout << m << n << endl;
while(i < m && j < n && path1[i] == path2[j]) {
resi = i; ++i; ++j;
}

return path1[resi];
}
};


leetcode: 236
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: