235 Lowest Common Ancestor of a Binary Search Tree

1 题目

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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given binary search tree:  root = [6,2,8,0,4,7,9,null,null,3,5]

Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

 Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Note:

All of the nodes' values will be unique.
p and q are different and both values will exist in the BST.

2 尝试解

2.1 分析

求二叉树中两个节点的最低公共父节点,可以将根节点到两个节点的路径都求出来,然后比较最低的公共节点。

2.2 代码

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == NULL) return root;
        vector<TreeNode*> path_p,path_q,temp;
        Get(root,p,path_p,temp);
        Get(root,q,path_q,temp);
        int i;
        for(i = 0; i < path_p.size() && i < path_q.size(); i++){
            if(path_p[i] != path_q[i]) break;
        }
        return path_p[i-1];
    }
    void Get(TreeNode* root, TreeNode* target, vector<TreeNode*>&path, vector<TreeNode*>&temp){
        if(path.size()==0 && root != NULL){
            temp.push_back(root);
            if(target != root){
                if(root->left!=NULL) Get(root->left,target,path,temp);
                if(root->right != NULL) Get(root->right,target,path,temp);
            }
            else{
                for(auto node : temp) path.push_back(node);
            }
            temp.pop_back();
        }            
    }
};

3 标准解

3.1 分析

利用二叉搜索树的性质,如果 p.val < root.val == q.val < root.val,即二者都大于或都小于root时,root就是二者的公共父节点,直到二者不等,分为位于root的左右子树中。

3.2 代码

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if ((root -> val > p -> val) && (root -> val > q -> val)) {
            return lowestCommonAncestor(root -> left, p, q);
        }
        if ((root -> val < p -> val) && (root -> val < q -> val)) {
            return lowestCommonAncestor(root -> right, p, q);
        }
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_39145266/article/details/89532942