1. 程式人生 > >[LeetCode]235 二叉查詢樹的最近公共父親節點

[LeetCode]235 二叉查詢樹的最近公共父親節點

Lowest Common Ancestor of a Binary Search Tree(二叉查詢樹的最近公共父親節點)

【難度:Easy】
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.

給定一個二叉查詢樹和所要查詢的兩個節點,找到這兩個節點的最近公共父親節點。如圖,節點2和8的LCA是6,節點2和4的LCA是2。

解題思路

根據LCA的定義和BST的特性,當root非空時可以區分為三種情況:1)兩個節點均在root的左子樹,此時對root->left遞迴求解;2)兩個節點均在root的右子樹,此時對root->right遞迴求解;3)兩個節點分別位於root的左右子樹,此時LCA為root。

c++程式碼如下:

/**
 * 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
(root == NULL) return root; if (p->val > root->val && q->val > root->val) { return lowestCommonAncestor(root->right,p,q); } else if (p->val < root->val && q->val < root->val) { return lowestCommonAncestor(root->left,p,q); } return root; } };