Algorithms—235.Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:表格中数据怎么求和 编辑:程序博客网 时间:2024/06/06 07:40
思路:二叉搜索树,直接判断p.val和q.val于root.val的大小,如果同向,则同侧继续判断,如果不同向,则返回root。
/** * 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==p) {return p;} if (root==q) {return q;} int ip=root.val-p.val; int iq=root.val-q.val; if (ip>0!=iq>0) { return root;}else {if (ip>0) {return lowestCommonAncestor(root.left,p,q);}else {return lowestCommonAncestor(root.right,p,q);}} }}
0 0
- Algorithms—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
- [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
- 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
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- HBase表设计原则整理
- git使用
- Matlab自动控制系统应用
- Mars老师的Android学习路线。
- Linux ip命令详解
- Algorithms—235.Lowest Common Ancestor of a Binary Search Tree
- 边的双连通分量问题
- Reverse Integer
- 各种数据库相关
- Android SurfaceView实战 带你玩转flabby bird (下)
- python-动态特性学习
- Mac的可执行脚本,类似于windows批处理脚本
- hive中map和reduce优化
- 页面之间传值