Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
题目:求二叉树的LCA,也就是两个节点的最低公共祖先。比如上图的二叉树,节点2和8的LCA是6,节点2和4的LCA是2。
思路:观察给定的二叉树可知,二叉树中任何节点:左节点的值 < 根节点的值 < 右节点的值。根据这个性质,可以做出如下判断:
Language : cpp
递归方法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (p->val < root->val && root->val > q->val)
return lowestCommonAncestor(root->left, p, q);
else if (p->val > root->val && root->val < q->val)
return lowestCommonAncestor(root->right, p, q);
else
return root;
}
};
Language : python
递归方法:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if p.val < root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root
迭代方法:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
while True:
if p.val < root.val > q.val:
root = root.left
elif p.val > root.val < q.val:
root = root.right
else:
return root