題目鏈接:
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
描述
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.
算法思想:
利用二叉樹的性質,在根的右側的數全部比根上的值要大,在樹根的左側的數全部比根上的值要小。這樣根據p、q節點上的值就可以判斷節點p、q是否在根的同一側了,如果不在同一側,其最小共同祖先即爲當前根,如果在同一側,則繼續判斷在哪一側,更新根節點。迭代過程。
源代碼
/*
Author:楊林峯
Date:2018.01.02
LeetCode(235):LCA
*/
/**
* 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) {
while((root->val - p->val) * (root->val - q->val) > 0)
{
if(root->val < p->val)
root = root->right;
else
root = root->left;
}
return root;
}
};