Given a binary tree, the tree two input nodes, they seek the lowest common ancestor.
Ancestor node of a tree node including itself.
note:
Binary input is not empty;
two input nodes must not empty, and is a node in the binary tree;
sample
binary tree [8, 12, 2, null , null, 6, 4, null, null, null, null] as shown below:
8
/
122
/
64
-
If the tree node is 2 and the input 12, the output of the lowest common ancestor tree node 8.
-
If the input node of the tree is 2 and 6, the lowest common ancestor of the output node of the tree 2.
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return NULL;
if(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 Left;
if(Right) return Right;
return NULL;
}
};