国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設計 > 正文

[LeetCode] Lowest Common Ancestor of a Binary Search Tree

2019-11-15 01:09:04
字體:
來源:轉載
供稿:網(wǎng)友
[LeetCode] Lowest Common Ancestor of a Binary Search Tree

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

According to thedefinition 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 allowa node to be a descendant of itself).”

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

For example, the lowest common ancestor (LCA) of nodes2and8is6. Another example is LCA of nodes2and4is2, since a node can be a descendant of itself according to the LCA definition.

這道題不難。主要是先要搞清楚LCA的定義。

然后LCA呢只會分為三種情況,如果P,Q中最大值的那個都小于root的值,那么LCA只能在左邊了。反正如果P,Q中最小值的那個都大于root的值,那么LCA肯定只能在右邊。如果這兩種情況都不是,那么就是最特殊的一種。LCA直接就是root。因為沒有辦法把這兩個node一起放在一邊子樹去了。

代碼如下。~

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {        if(root==null){            return null;        }        if(Math.max(p.val,q.val)<root.val){           return lowestCommonAncestor(root.left,p,q);        }else if(Math.min(p.val,q.val)>root.val){            return lowestCommonAncestor(root.right,p,q);        }        return root;    }}


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 新邵县| 博罗县| 三河市| 怀来县| 甘南县| 长岛县| 邢台县| 大埔县| 肃宁县| 乾安县| 嘉祥县| 旬邑县| 司法| 龙里县| 潜江市| 富顺县| 湛江市| 淮南市| 固安县| 连平县| 稷山县| 东至县| 称多县| 建德市| 大邑县| 南华县| 西宁市| 烟台市| 浦北县| 施甸县| 崇文区| 乌拉特后旗| 包头市| 玉龙| 德钦县| 凌云县| 景洪市| 礼泉县| 仁布县| 保山市| 富民县|