这道题承接Unique Binary Search Trees,只需要返回搜索二叉树的个数,用DP求解。但是这道题需要得到所有树的集合,可以用DFS求解。
原题是这个样子的:
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's...
分类:
其他好文 时间:
2014-12-17 00:23:26
阅读次数:
191
Given a binary search tree(BST), find the lowest common ancestor of two given nodes in the BST.Node* LCA(Node* root, Node* p, Node* q){ if (!root |...
分类:
其他好文 时间:
2014-12-17 00:13:50
阅读次数:
172
public TreeNode sortedListToBST(ListNode head) {
if (head == null)
return null;
int len = 0;
ListNode nextNode = head;
while (nextNode != null) {
nextNode = nextNode.next;
len++;
}
return buildTree(head, 0, len - 1);
}
public Tree...
分类:
其他好文 时间:
2014-12-16 21:05:05
阅读次数:
159
题目:Givenn, how many structurally uniqueBST's(binary search trees) that store values 1...n?For example,Givenn= 3, there are a total of 5 unique BST's. ...
分类:
其他好文 时间:
2014-12-14 18:30:16
阅读次数:
176
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.解题思路:找到链表的中点,作为根,前端作为左子树,后端作为右子树,并对前后做递归操...
分类:
其他好文 时间:
2014-12-13 13:21:52
阅读次数:
153
题目
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
解答
题目要求将链表转化为二叉查找树。利用树的中序遍历的递归思想,对链表结点一个个进行访问,先对左子树进行递归,然后将当前结点作为根,迭代到下一个链表结点,最后在递...
分类:
其他好文 时间:
2014-12-12 19:04:40
阅读次数:
127
思路:把数字排序,排序后数字列,中间点为父节点,左边部分为左子树,右边为右子树。
假设节点定义为:
// Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), ...
分类:
其他好文 时间:
2014-12-11 12:31:45
阅读次数:
126
【题目】
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n)
space is pretty straight forward. Could...
分类:
其他好文 时间:
2014-12-10 12:35:23
阅读次数:
191
Givenn, how many structurally uniqueBST's(binary search trees) that store values 1...n?For example,Givenn= 3, there are a total of 5 unique BST's. 1 ....
分类:
其他好文 时间:
2014-12-09 13:54:28
阅读次数:
205
背景铺垫假设我们正在设计一个翻译程序,讲英语翻译成法语,需要用一棵BST存储文章中出现的单词及等价的法语。因为要频繁地查找这棵树,所以我们希望查找时间越短越好。当然我们可以考虑使用红黑树,或者可能更适用的伸展树,来实现这一操作。但是这仍然不能满足我们的需要:由于单词出现频率不同,如果mycophag...
分类:
其他好文 时间:
2014-12-06 12:49:23
阅读次数:
279