I, entitled Description
Title 236. Lowest Common Ancestor of a Binary Tree, find two nodes in a binary tree common ancestor. The difficulty is Medium!
Second, my answer
The binary tree recursive traversal, slightly modified to:
class Solution{
public:
TreeNode* lowestCommonAncestor(TreeNode* root,TreeNode*p,TreeNode*q){
if(root == NULL) return root;
if(root == p || root==q) return root;
TreeNode* left,*right;
left = lowestCommonAncestor(root->left,p,q);
right = lowestCommonAncestor(root->right,p,q);
if(left !=NULL && right!=NULL){
return root;
}else if(left != NULL){
return left;
}else if(right != NULL){
return right;
}else{
return NULL;
}
}
};
Properties are as follows:
Runtime: 16 ms, faster than 94.88% of C++ online submissions for Lowest Common Ancestor of a Binary Tree.
Memory Usage: 16.7 MB, less than 87.27% of C++ online submissions for Lowest Common Ancestor of a Binary Tree.
Third, the optimization measures
Other methods, temporarily can not remember.