-
Notifications
You must be signed in to change notification settings - Fork 250
Open
Labels
LeetcodeLeetcode的题目Leetcode的题目
Description
/**
* 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 || root == p || root == q)
return root;
let left = lowestCommonAncestor(root.left, p, q); //在左子树中查找p和q
let right = lowestCommonAncestor(root.right, p, q); //在右子树中查找p和q
/**
* left为null,说明p和q在右子树(right)中
* right为null,说明p和q在左子树(left)中
* left和right都不为null,说明p和q分别存在于root的左右子树中
*/
return left == null ? right : (right == null ? left : root);
}Metadata
Metadata
Assignees
Labels
LeetcodeLeetcode的题目Leetcode的题目