Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]
来源:互联网 发布:乐高ev3编程软件简介 编辑:程序博客网 时间:2024/05/02 01:02
题目:
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.
翻译:
给定一个搜索二叉树,找到给定的2个节点的最小共同祖先(LCA)。
根据维基百科对LCA的定义,最小共同祖先是定义在树T中的一个最小节点,这个最小节点满足,树上的另外2个节点v和w都是它的子孙(这里我们允许一个是它自己的子孙)。
例如上图中的2和8的LCA是6,2和4的LCA是2。
分析:
这道题的思路是从根节点这个共同祖先的节点开始,根据搜索二叉树的性质,也就是任一节点的左子树的所有节点的值一定会比该节点的小,右子树一定会比该节点大,一步步找到最小的共同祖先。
而如果遍历到某一节点时,2棵子树的值既没有都比该节点小,也没有都比该节点大,只有2种可能:第一种可能是2棵子树的值,一个比该节点大,一个比该节点小;另外一种可能其中至少有一个子树的值等于该节点。不管是哪种可能,这个时候最小共同祖先都为该节点。
代码:
/** * 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; }}
- Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]
- 235. Lowest Common Ancestor of a Binary Search Tree(Tree-Easy)
- 235. Lowest Common Ancestor of a Binary Search Tree [easy] (Python)
- Easy-题目14:235.Lowest Common Ancestor of a Binary Search Tree
- Leetcode 235. Lowest Common Ancestor of a Binary Search Tree (Easy) (cpp)
- 235. Lowest Common Ancestor of a Binary Search Tree 难度:easy
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- 235.Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree LeetCode
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- Quartz.NET开发指南教程
- jquery 替换原来的html内容
- mysql杂记
- 可视化分析工具Qlik进阶
- 翻翻git之---偏向iOS风格的Switch ToggleSwitch
- Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]
- Spring实现AOP的4种方式
- 修改浏览器地址
- 发生系统错误 1275.此驱动程序被阻止加载
- vs2013 类库自动添加作者版本信息
- Deepin linux下安装netbeans
- Roman to Integer/Integer to Roman
- HDU 5459 Jesus Is Here dp+预处理
- Java实现冒泡排序算法