Topic
Given a binary search tree, find the nearest common ancestor of the two specified nodes of the tree.
Baidu Encyclopedia recent common ancestor as defined: "For two nodes of the root of the tree T p, q, is represented as a common ancestor node x, that x is p, q ancestor depth as large as possible and x (a node can be its own ancestors). "
For example, given the following binary search tree: root = [6,2,8,0,4,7,9, null, null, 3,5]
Input: root = [6,2,8,0,4,7,9, null, null, 3,5], p = 2, q = 8
Output: 6
Explanation: nodes 2 and 8 is the common ancestor 6.
Input: root = [6,2,8,0,4,7,9, null, null, 3,5], p = 2, q = 4
Output: 2
Explanation: nodes 2 and 4 are common ancestor 2, because by definition a recent common ancestor node can be a node itself.
Thinking
The characteristics of the binary search tree, p, q any one of equal to the parent node, returns, p, q are smaller than the parent node values are in the left tree continues, is greater than the parent value is continued in the right tree, a parent node is greater than, a value smaller than the parent node, the parent node returns
/**
* 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) {
return null
}
if (p.val === root.val) {
return p
} else if (q.val === root.val) {
return q
} else if (root.val > p.val && root.val > q.val) {
return lowestCommonAncestor(root.left, p, q)
} else if (root.val < p.val && root.val < q.val) {
return lowestCommonAncestor(root.right, p, q)
} else if ((root.val < p.val && root.val > q.val) || (root.val > p.val && root.val < q.val)) {
return root
}
};
// 迭代版本
var lowestCommonAncestor = function (root, p, q) {
if (!root) {
return null
}
while (root) {
if (p.val === root.val) {
return p
} else if (q.val === root.val) {
return q
} else if (p.val < root.val && q.val < root.val) {
root = root.left
} else if (p.val > root.val && q.val > root.val) {
root = root.right
} else if ((p.val > root.val && q.val < root.val) || (p.val < root.val && q.val > root.val)) {
return root
}
}
return null
};