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).”
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.
给定一个二叉树和所要查找的两个节点,找到两个节点的最近公共父亲节点(LCA)。比如,节点5和1的LCA是3,节点5和4的LCA是5。
解题思路
本题与LeetCode 235的区别就是由二叉查找树变为了二叉树,即数据从有序变为了无序,那么就不能通过root的值和两个节点的值的大小关系来划分查找区域。在题235的代码基础做了些许变动,同样使用递归搜索的方法,当root非空时,对root->left和root->right分别进行搜索。若搜索结果均非空,说明两个节点分别位于左右子树之中,LCA则为root;若只有一个结果为空,则LCA是另一个非空的节点;若结果均空,则返回NULL。
c++代码如下:
/**
* 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 || root == p || root == q)
return root;
TreeNode* left = lowestCommonAncestor(root->left,p,q);
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if (left && right)
return root;
if (!left)
return right;
if (!right)
return left;
}
};