二叉搜索数求最近公共祖先
2016-05-22 19:31
375 查看
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Stack; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { //递归解法 public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) { if(p.val < root.val && q.val < root.val){ return lowestCommonAncestor(root.left, p, q); }else if(p.val > root.val && q.val > root.val){ return lowestCommonAncestor(root.right, p, q); }else { return root; } } //非递归,先求路径 LinkedList<TreeNode> getPath(TreeNode root, TreeNode node){ LinkedList<TreeNode> path = new LinkedList<>(); path.push(root); if(node == root){ return path; } TreeNode temp = root; while (temp != null){ if(node.val < temp.val){ temp = temp.left; }else if(node.val > temp.val){ temp = temp.right; } path.push(temp); if(node.val == temp.val){ break; } } return path; } public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) { LinkedList<TreeNode> pPath = getPath(root, p); LinkedList<TreeNode> qPath = getPath(root, q); int i = 0; int dif = pPath.size() - qPath.size(); if (dif > 0){ i = dif; while (i-- > 0){ pPath.pop(); } }else if(dif < 0){ i = -dif; while (i-- > 0){ qPath.pop(); } } TreeNode pNode,qNode; while (!pPath.isEmpty()){ pNode = pPath.poll(); qNode = qPath.poll(); if(pNode.val == qNode.val){ return pNode; } } return null; } }
相关文章推荐
- javascript数据结构之二叉搜索树实现方法
- C#创建二叉搜索树的方法
- Python实现二叉搜索树
- Python二叉搜索树与双向链表转换实现方法
- Python二叉搜索树与双向链表转换实现方法
- 数据结构-二叉搜索树(Binary Search Tree)的C++实现模板
- LCA模板
- 二叉搜索树
- 【LCA】SPOJ QTREE2
- LeetCode:Convert Sorted Array to Binary Search Tree
- 二叉搜索树的后序遍历序列
- poj3728
- hihocoder #1067 LCA
- hihocoder #1069 线段树
- POJ1330 Nearest Common Ancestors 非lca pascal 解题报告
- POJ1986 Distance Queries LCA pascal 解题报告
- 二叉搜索树的c++实现(含深复制)
- 树上倍增实现lca
- Leetcode:Binary Search Tree Iterator
- Introduce to algorithm--------pseudo code to C/C++ code(chapter 12)