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).”
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4
For example, the lowest common ancestor (LCA) of nodes 5
and 1
is 3
. Another example is LCA of nodes 5
and 4
is 5
, since a node can be a descendant of itself according to the LCA definition.
Solution:
This is a binary tree so each node only has two children. If the tree is not empty and the two nodes are in the tree. Then there should be two circumstances: 1 two nodes are in the same branch, for example, 1 and 8, then we should return the upper one. 2 two nodes are in different branches, then, we should return the their common root.
So for each node we should get the results of the left and result of the right. if both of them are not empty then return root. if left if empty return right, if right is empty return left. Now let’s think about the terminal conditions. if it goes to leaf nodes, their children are both NULL. If root is NULL return NULL.
/**
* 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 == NULL) return root;//终止条件,为NULL时返回
if (root == p || root == q) return root;//从上向下搜,当搜到root为p或q的时候就直接返回,如果p和q都在此分支下面就不用继续搜索,如果不是,就返回p,q到上一层
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root; //如果在不同分支就return root,一定return 上级
if (left == NULL) return right;
if (right == NULL) return left;
}
};