(http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html) Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. Code: BinaryTree* sortedListToBST(ListNode *& list, int start, int…
(http://leetcode.com/2010/11/convert-sorted-array-into-balanced.html) Given an array where elements are sorted in ascending order, convert it to a height balanced BST. Code: BinaryTree* sortedArrayToBST(int arr[], int start, int end) { if (start > en…
题目:将非递减有序的链表转化为平衡二叉查找树! 参考的博客:http://blog.csdn.net/worldwindjp/article/details/39722643 利用递归思想:首先找到链表的中间节点,于是链表被分为了由该中间节点划分开来的两部分.递归地处理这两部分,最终便得到了平衡二叉查找树. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * Lis…
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 || !p || !q) return NULL; if (max(p->data, q->data) < root->data) return LCA(root->left, p,…
1099 Build A Binary Search Tree(30 分) A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a nod…
UVA 1264 - Binary Search Tree 题目链接 题意:给定一个序列,插入二叉排序树,问有多少中序列插入后和这个树是同样的(包含原序列) 思路:先建树,然后dfs一遍,对于一个子树而言,仅仅要保证左边和右边顺序对就能够了,所以种数为C(左右结点总数,左结点),然后依据乘法原理乘上左右子树的情况就可以 代码: #include <cstdio> #include <cstring> typedef long long ll; const int MAXNODE =…
题目链接 Observations 含有 $n$ 个点且 key(以下也称 key 为「权值」)是 1 到 $n$ 的 BST 具有下列性质: 若 $k$ 是一个非根叶子且是个左儿子,则 $k$ 的父亲是 $k+1$ . 证明:假设 $k$ 的父亲是 $p$ 且 $p \ne k + 1$,则 $p > k + 1$:显然 $k + 1$ 不可能是 $k$ 的祖先. 设 $k$ 和 $k + 1$ 的最近公共祖先是 $t$,则有 $k < t < k + 1$ 或者 $ k + 1 &l…
(http://leetcode.com/2010/11/convert-binary-search-tree-bst-to.html) Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list. Code: v…
Use one queue + size variable public class Solution { public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { ArrayList result = new ArrayList(); if (root == null) return result; Queue<TreeNode> queue = new LinkedList<TreeNod…
Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9/22/2015 Go over one example to build some muscle memory about this bottom up, O(1) solution to find the root node in subtree function. Sorted List: 1…