236. Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:linux 日志切割脚本 编辑:程序博客网 时间:2024/06/03 20:20
寻找最低共同父节点(LCA)
代码如下:
public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null){ //one in left, one in right return root; }else if (left != null && right == null){ //both in the left return left; }else if (left == null && right != null){ //both in the right return right; }else return null; }}
解释:
lowestCommonAncestor用来检查某个subtree是否包含p和q其中的至少1个
0 0
- 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
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- LeetCode------------single-number-ii
- noip2013积木大赛
- Oracle 的过程和函数
- hdu3526(最小费用流)
- 异步任务下载网络图片
- 236. Lowest Common Ancestor of a Binary Tree
- ViewPager详解(一)简单介绍
- AngularJS: $broadcast $emit $on
- [LeetCode-Java]35. Search Insert Position
- 微信小程序:MINA视图层
- Oracle 自定义结构(Record)
- dijkstra和spfa
- 我在中东肝PS
- noip2013花匠