Lowest Common Ancestor of a Binary Tree | Java最短代码实现
来源:互联网 发布:淘宝三个评价 编辑:程序博客网 时间:2024/05/17 03:45
原题链接:236. Lowest Common Ancestor of a Binary Tree
【思路】
和 Lowest Common Ancestor of a Binary Tree 不同的是。此二叉树的值可能有重复,并且节点上的大小顺序没有规律,那么就只能采用深度遍历。但是可以肯定的是p,q节点一定是分居最低在共同祖先的左右两侧(p或q本身为祖先除外):
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) return null; if (root == p || root == q) return root; TreeNode leftSub = lowestCommonAncestor(root.left, p, q); TreeNode rightSub = lowestCommonAncestor(root.right, p, q); if (leftSub != null && rightSub != null) return root; return leftSub != null ? leftSub : rightSub; }
31 / 31 test cases passed. Runtime: 12 ms Your runtime beats 73.85% of javasubmissions.
欢迎优化!
1 0
- 235. Lowest Common Ancestor of a Binary Search Tree | Java最短代码实现
- Lowest Common Ancestor of a Binary Tree | Java最短代码实现
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree(***)
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- UIView如何管理它的子视图
- HttpResponseMessage && IHttpActionResult
- 公用分页模块之knockout
- 让 UIAlertController 兼容 iOS7
- TF400976: SQL Server 服务帐户 NT Service\MSSQLSERVER 没有在备份路径 \\XXX\XX 创建备份的必要权限
- Lowest Common Ancestor of a Binary Tree | Java最短代码实现
- 同步或者重构Activiti Identify用户数据的多种方案比较
- 图片处理
- Hadoop的namenode datanode无法启动
- FastDFSClient.java工具方法
- 第二堂课
- 获取指定包下的所有类
- 如何优(zhuang)雅(bi)的使用chrome控制台
- 个人学习android的基本知识记录