Lowest Common Ancestor of a Binary Search Tree
2016-07-11 15:21
363 查看
/** * 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 (root.val > p.val && root.val > q.val) { return lowestCommonAncestor(root.left, p, q); } else if (root.val < p.val && root.val < q.val) { return lowestCommonAncestor(root.right, p, q); } else { return root; } } // public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { // if (root == null || root == p || root == q) { // return root; // } // TreeNode ln = lowestCommonAncestor(root.left, p, q); // TreeNode rn = lowestCommonAncestor(root.right, p, q); // if (ln != null && rn != null) { // return root; // } // if (ln != null) { // return ln; // } // if (rn != null) { // return rn; // } // return null; // } }
相关文章推荐
- MySql数据库查询结果用表格输出PHP代码示例
- SQL的基本操作
- iOS 富文本
- android 打包成jar包(转)
- 关于C# Dockpanel的一些入门的基本操作
- 怎么设置 运行bat 文件不弹出CMD窗口
- struts2 标签<s:submit />怎么加css样式(
- java web项目开发环境
- nginx优化
- python脚本――自动推送txt,EXCEL等文件模板
- SSH面试题
- xamarin真的是一个鸡肋吗?
- listView使用小技巧P66--P76
- sturct stat 结构体中 st_mode 的含义
- JavaScript重难点基础笔记
- nyoj 84 阶乘的0
- IP、TCP、UDP数据包长度问题
- BroadcastReceiver 之强制下线
- hdu5386(模拟)
- 数据库分类