236. Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:什么是矩阵图片 编辑:程序博客网 时间:2024/06/16 02:53
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
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).”
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4
For example, the lowest common ancestor (LCA) of nodes 5
and 1
is 3
. Another example is LCA of nodes 5
and 4
is 5
, since a node can be a descendant of itself according to the LCA definition.
Subscribe to see which companies asked this question
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private boolean search(TreeNode root,TreeNode p,List<TreeNode> ret){ if(root==null)return false; ret.add(root); if(root==p){ // ret.add(root.val); return true; } if(search(root.left,p,ret)==true)return true; if(search(root.right,p,ret)==true)return true; ret.remove(ret.size()-1); return false; } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { List<TreeNode> ret1 = new ArrayList<>(); List<TreeNode> ret2 = new ArrayList<>(); search(root,p,ret1); search(root,q,ret2); TreeNode ret = null; int len = Math.min(ret1.size(),ret2.size()); for(int i = 0;i<len;++i){ if(ret1.get(i)==ret2.get(i))ret = ret1.get(i); else break; } return ret; }}
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
- java并发 之 CAS详解
- 16. 3Sum Closest
- ionic & AngularJS 传递url类型的参数
- java.lang.ClassNotFoundException: com.google.common.primitives.Ints
- java中静态代码块的用法 static用法详解
- 236. Lowest Common Ancestor of a Binary Tree
- Android 获取手机号
- 解决:eclipse下搜索到文件却不显示文件名
- ajax不执行异步方法,直接执行error回调函数
- idea 15 破解
- 提升网站页面打开速度的12个建议
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- python系列之 RabbitMQ - work queues
- BeautifulSoup学习笔记