[LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
2016-03-07 10:51
381 查看
Problem Description
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.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).”
[]https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/]
思路
没看清题目,没注意是BST,所以写了个一般二叉树的。。具体思路请看[]http://blog.csdn.net/u012468264/article/details/50817712]
Code
package q236; import java.util.*; import TreeNode.*; public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { List<List<TreeNode>> path = new ArrayList<List<TreeNode>>(); List<TreeNode> tmp = new ArrayList<TreeNode>(); tmp.add(root); helper(tmp, root, p, path); helper(tmp, root, q, path); for (int i = path.get(0).size() - 1; i >= 0; i--) { for (int j = path.get(1).size() - 1; j >= 0; j--) { if (path.get(0).get(i) == path.get(1).get(j)) return path.get(0).get(i); } } return null; } public void helper(List<TreeNode> path, TreeNode root, TreeNode target, List<List<TreeNode>> ans) { if (root == target) { ans.add(new ArrayList<TreeNode>(path)); return; } else { if (root.left != null) { path.add(root.left); helper(path, root.left, target, ans); path.remove(path.size() - 1); } if (root.right != null) { path.add(root.right); helper(path, root.right, target, ans); path.remove(path.size() - 1); } } } // public static void main(String[] args) { // Solution s = new Solution(); // Codec c = new Codec(); // TreeNode root = c // .deserialize("6,2,8,0,4,7,9,null,null,3,5,null,null,null,null"); // TreeNode p = c.getNode(root, 2); // TreeNode q = c.getNode(root, 8); // // System.out.println(p.val); // // System.out.println(q.val); // TreeNode ans = s.lowestCommonAncestor(root, p, q); // System.out.println(ans.val); // // } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解