Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.
The definition of the nearest common ancestor in Baidu Encyclopedia is: "For two nodes p and q of the rooted tree T, the nearest common ancestor is expressed as a node x, so that x is the ancestor of p and q and the depth of x is as large as possible (A node can also be its own ancestor)."
For example, given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
If there is no left (right) subtree, return to the first right (left) subtree found,
If the left and right subtrees are found, the root node is returned directly
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null||root==p||root==q){
return root;
}
TreeNode ps =lowestCommonAncestor(root.left,p,q);
TreeNode qs =lowestCommonAncestor(root.right,p,q);
if(ps==null){
return qs;
}
if(qs==null){
return ps;
}
return root;
}
}