博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 【235. Lowest Common Ancestor of a Binary Search Tree】
阅读量:7190 次
发布时间:2019-06-29

本文共 1373 字,大约阅读时间需要 4 分钟。

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the : “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).”

_______6______       /              \    ___2__          ___8__   /      \        /      \   0      _4       7       9         /  \         3   5

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.

 

思路1.分别和当前节点比较(最开始是根节点)如果p->val和q->val一个大于当前节点值,一个小于当前节点值,则表示当前节点是他们的最低公共祖先,如果两个的大于当前节点的值,则递归调用右子树,如果都小于,则递归调用左子树。

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

  

转载于:https://www.cnblogs.com/rockwall/p/5744265.html

你可能感兴趣的文章
我自研主动型氢原子钟将现身空间站
查看>>
maven添加本地jar包
查看>>
PHP 重置数组为连续数字索引的方式
查看>>
致创业者:APP已死 服务永生
查看>>
解决TIME_WAIT过多造成的问题
查看>>
mysql 主从同步故障解决 Error 'Row size too large (> 8126).
查看>>
16位纯数字MD5
查看>>
腾讯面试
查看>>
数据备份就用多备份
查看>>
企业如何进行IT基础设施规划
查看>>
我的友情链接
查看>>
iOS面试题第一波
查看>>
在centos中安装puppet和安装过程的一些错误解决
查看>>
html元素
查看>>
使用kaptcha生成验证码
查看>>
Maven学习总结(四)——Maven核心概念
查看>>
python 连接mongodb ,并将EXCEL文档导入mongodb
查看>>
第三节 在shell脚本中进行for循环
查看>>
Java Script 中定义对象的几种方式
查看>>
mysql编译安装完成后,启动时报错The server quit without updating PID file
查看>>