寻找二叉树中任意两个节点的最近公共父节点。
初始的root节点肯定是这两个节点的公共父节点。不妨从root节点开始一层层查找节点root_使得p和q分居root_两侧,那么这个root_肯定是符合条件的最近公共父节点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if( root==null || root == p || root == q )
{
return root;
}
TreeNode left = lowestCommonAncestor(root.left,p,q);
TreeNode right = lowestCommonAncestor(root.right,p,q);
if( left != null && right != null )
{
return root;
}
return left != null ? left:right;
}
}