面试题6:二叉树最近公共节点(LCA)《leetcode236》

时间:2020-12-01 09:40:30

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).” 
面试题6:二叉树最近公共节点(LCA)《leetcode236》 
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。

 class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root,TreeNode* p,TreeNode* q){
if(root == nullptr || 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 == nullptr) return right;
if(right == nullptr) return left;
}
};