[leetcode]: 235. Lowest Common Ancestor of a Binary Search Tree

来源:互联网 发布:2014新疆网络管制 编辑:程序博客网 时间:2024/05/21 09:50

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 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).”
这里写图片描述
给一棵二叉搜索树,树上的两个节点v,w,求这两个节点的最低公共祖先
例如,节点2,8的最低公共祖先为6. 节点2,4的最低公共祖先为2.

2.分析

二叉搜索树BST满足,左节点的值<根节点的值<右节点的值。
所以从根节点开始往下搜索,如果:
当前节点值>两个节点的值,转到左子树
当前节点值<两个节点的值,转到右子树
介于两者直接,则找到了最低公共子节点。

题外话:如果不是BST,只是一棵普通的二叉树,那么这个问题就转换为求两个链表的第一个公共节点。分别求从根节点到指定节点的路径,然后找这两条路径的第一个汇合点。

3.代码

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {    int maxv = p->val > q->val ? p->val : q->val;    int minv = p->val + q->val - maxv;    while (root) {        if (root->val > maxv)            root = root->left;        else if (root->val < minv)            root = root->right;        else            return root;    }}
阅读全文
0 0