日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]

發(fā)布時(shí)間:2024/2/28 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy] 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目:
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).”

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.

翻譯:
給定一個(gè)搜索二叉樹(shù),找到給定的2個(gè)節(jié)點(diǎn)的最小共同祖先(LCA)。
根據(jù)維基百科對(duì)LCA的定義,最小共同祖先是定義在樹(shù)T中的一個(gè)最小節(jié)點(diǎn),這個(gè)最小節(jié)點(diǎn)滿(mǎn)足,樹(shù)上的另外2個(gè)節(jié)點(diǎn)v和w都是它的子孫(這里我們?cè)试S一個(gè)是它自己的子孫)。
例如上圖中的2和8的LCA是6,2和4的LCA是2。

分析:
這道題的思路是從根節(jié)點(diǎn)這個(gè)共同祖先的節(jié)點(diǎn)開(kāi)始,根據(jù)搜索二叉樹(shù)的性質(zhì),也就是任一節(jié)點(diǎn)的左子樹(shù)的所有節(jié)點(diǎn)的值一定會(huì)比該節(jié)點(diǎn)的小,右子樹(shù)一定會(huì)比該節(jié)點(diǎn)大,一步步找到最小的共同祖先。
而如果遍歷到某一節(jié)點(diǎn)時(shí),2棵子樹(shù)的值既沒(méi)有都比該節(jié)點(diǎn)小,也沒(méi)有都比該節(jié)點(diǎn)大,只有2種可能:第一種可能是2棵子樹(shù)的值,一個(gè)比該節(jié)點(diǎn)大,一個(gè)比該節(jié)點(diǎn)小;另外一種可能其中至少有一個(gè)子樹(shù)的值等于該節(jié)點(diǎn)。不管是哪種可能,這個(gè)時(shí)候最小共同祖先都為該節(jié)點(diǎn)。

代碼:

/*** 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) {TreeNode LCA=root;while(true){if(p.val<LCA.val&&q.val<LCA.val){LCA=LCA.left;}else if(p.val>LCA.val&&q.val>LCA.val){LCA=LCA.right;}else{break;}}return LCA;} }

總結(jié)

以上是生活随笔為你收集整理的Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。