原创 [geeks]Construct Full Binary Tree from given preorder and postorder traversals
思路:根據先序和後序遍歷數據,遞歸的構造整棵樹 struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), lef
原创 [Tree]If you are given two traversal sequences, can you construct the binary tree?
If you are given two traversal sequences, can you construct the binary tree? August 2, 2009 It depends on what tr
原创 [Tree]樹與先序遍歷
如果我們有一個先序遍歷的數組或者一個鏈表,以它們來建立一棵樹,但是又無法很好的劃分左右子樹,可以用下面的框架。 TreeNode *buildTree(vector<int> &preorder, int &cur, int min,
原创 [Leetcode]Search a 2D Matrix
思路:用經典的二分查找,先找到所在行,然後再找到所在列class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) {
原创 [Leetcode]Best Time to Buy and Sell Stock III
思路:III限制了只能進行兩次交易,問題可以轉化成在兩個不重疊區間找到i和j(i<j)可以使Aj - Ai,即在區間[0..i]和[i..n-1]兩個區間尋找最優的一次交易。時間複雜度是O(N^2),可以優化分別用O(N)的時間計算[0.
原创 [geeks]Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST
思路:同leetcode中Recover Binary Search Tree
原创 [劍指Offer]二維數組中的查找
思路:這題二維矩陣少了Leetcode中的一個限制,就是這一行的最左邊的值並一定比前一行的最右邊的值大。我們同樣也是先找到所在行,然後在該行二分查找,但是定位所在行的方式需要改變。 #include <iostream> #includ
原创 [劍指offer]用兩個棧實現隊列
思路:一個棧用來入隊,另外一個棧用來出隊 #include <iostream> #include <cstdio> #include <vector> #include <stack> #include <string> using n
原创 [Leetcode]Merge Sorted Array
思路:從後往前merge,這樣可以不用額外的空間 class Solution { public: void merge(int A[], int m, int B[], int n) { // Start typ
原创 [劍指offer]替換空格
思路:與leetcode 裏的 Merge Sorted Array相似 #include <iostream> #include <cstdio> #include <vector> #include <string> using n
原创 [Leetcode]Distinct Subsequences
思路:計數問題往往用DP class Solution { public: int numDistinct(string S, string T) { // Start typing your C/C++ solu
原创 [Leetcode]Triangle
空間O(N^2) class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { // Start typing your C
原创 [Tree]樹與中序遍歷
對一棵二叉樹進行中序遍歷得到a0 a1...an... 當遍歷樹時,如果處理當前節點時需要其中序遍歷序列中前一個節點的信息,即訪問an時需要an-1那麼可以用下面的框架進行中序遍歷。 void fun(TreeNode *root, T
原创 [劍指offer]從頭到尾打印鏈表
簡單題:用棧或者遞歸
原创 [geeks]Construct BST from given preorder traversal
思路一:preorder數組的第一個元素爲根,然後從左到右開始找第一個大於根的元素,遞歸的構造左右子樹,時間複雜度O(n)。 思路二:一邊遍歷preorder數組一邊構造BST struct TreeNode { int val; T