Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]
題目:
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)題。
- 上一篇: Leet Code OJ 223. Re
- 下一篇: Leet Code OJ 219. Co