题目描述:
Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
Notice
Assume two nodes are exist in tree.
Example
题目思路:
For the following binary tree:
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
这题我用了BFS的想法,从root开始一层层往下找,对于每个node,都判断它是不是既有A又有B,如果是,就把答案更新为这个node。由于这个node的level会越来越往下,那么当我找完所有的node的时候,最后的答案就是所求的了。
Mycode(AC = 31ms):
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
// write your code here
if (root == NULL) {
return NULL;
}
TreeNode *ans = root;
stack<TreeNode *> treeHelper;
treeHelper.push(root);
while (!treeHelper.empty()) {
TreeNode *node = treeHelper.top();
treeHelper.pop();
if (isChild(node, A) && isChild(node, B)) {
ans = node;
if (node->left) {
treeHelper.push(node->left);
}
if (node->right) {
treeHelper.push(node->right);
}
}
}
return ans;
}
bool isChild(TreeNode *root, TreeNode *node) {
if (root == NULL) {
return false;
}
if (root->val == node->val) {
return true;
}
return isChild(root->left, node) || isChild(root->right, node);
}
};