LeetCode 235: Lowest Common Ancestor of a Binary Search Tree

题目链接:

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).”
LeetCode 235: Lowest Common Ancestor of a Binary Search Tree_第1张图片
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;
    }
};

你可能感兴趣的:(leetcode,算法,leetcode)