Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
注意这里是普通的二叉树,没有顺序的,所以就要老老实实的查找。
如果跟节点和要查找的节点为空,就返回空,如果要查找的节点不存在于左边,就在右边找,如果不存在于右边,就在左边找,否则就是一左一右,那么就返回当前跟节点了。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
if(root==p||root==q)return root;
if(root===null || p===null || q===null)return null;
var leftN=lowestCommonAncestor(root.left,p,q);
var rightN=lowestCommonAncestor(root.right,p,q);
if(leftN===null) return rightN;
else if(rightN===null) return leftN;
else return root;
};