diff --git a/100.txt b/100.txt new file mode 100644 index 0000000..e699c40 --- /dev/null +++ b/100.txt @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + //check the node itself + if(p==NULL && q==NULL) return true; + else + if(p==NULL||q==NULL) return false; + else + { + if(p->val != q->val) return false; + else + //check the child nodes + isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } + } +}; \ No newline at end of file diff --git a/101.txt b/101.txt new file mode 100644 index 0000000..a9ef5e9 --- /dev/null +++ b/101.txt @@ -0,0 +1,95 @@ +Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). + +For example, this binary tree is symmetric: + + 1 + / \ + 2 2 + / \ / \ +3 4 4 3 + +But the following is not: + + 1 + / \ + 2 2 + \ \ + 3 3 + +Note: +Bonus points if you could solve it both recursively and iteratively. + +confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. + +OJ's Binary Tree Serialization: + +The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. + +Here's an example: + + 1 + / \ + 2 3 + / + 4 + \ + 5 + +The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +// use recursion +class Solution { +public: + bool DFS(TreeNode* left, TreeNode* right) + { + if(left == NULL && right == NULL) return true; + if(left == NULL || right == NULL) return false; + if(left->val != right->val) return false; + else + return DFS(left->left,right->right) && DFS(left->right, right->left); + } + bool isSymmetric(TreeNode* root) { + if(root == NULL) return true; + return DFS(root->left, root->right); + } +}; + +// use two queues to record the left and right branch +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if(root == NULL) return true; + TreeNode *left, *right; + queue q1, q2; + q1.push(root->left); + q2.push(root->right); + while(!q1.empty() && !q2.empty()) + { + left = q1.front(); + q1.pop(); + right = q2.front(); + q2.pop(); + + if(left == NULL && right == NULL) continue; + if(left == NULL || right == NULL) return false; + if(left->val != right->val) return false; + else + { + q1.push(left->left); + q1.push(left->right); + q2.push(right->right); + q2.push(right->left); + } + } + return true; + } +}; \ No newline at end of file diff --git a/104.txt b/104.txt new file mode 100644 index 0000000..8832aff --- /dev/null +++ b/104.txt @@ -0,0 +1,20 @@ +//Maximum Depth of Binary Tree + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int maxDepth(TreeNode* root) { + if (root == NULL) + return 0; + else + return 1 + max(maxDepth(root->left), maxDepth(root->right)); + } +}; \ No newline at end of file diff --git a/110.txt b/110.txt new file mode 100644 index 0000000..7fdda81 --- /dev/null +++ b/110.txt @@ -0,0 +1,50 @@ +Given a binary tree, determine if it is height-balanced. +For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +// top to down +class Solution { +public: + int depth(TreeNode* root){ + if(root == NULL) + return 0; + else + return max(depth(root->left), depth(root->right)) + 1; + } + bool isBalanced(TreeNode* root) { + if(root == NULL) return true; + int ld = depth(root->left); + int rd = depth(root->right); + if(abs(ld-rd) > 1) + return false; + else + return isBalanced(root->left) && isBalanced(root->right); + } +}; + +// bottom up +class Solution { +public: + //if not balance ,return -1; else return the depth + int balanceness(TreeNode* root){ + if(root == NULL) return 0; + int ld = balanceness(root->left); + if(ld == -1) return -1; + int rd = balanceness(root->right); + if(rd == -1) return -1; + if(abs(ld - rd) > 1) return -1; + return max(ld, rd) + 1; + } + bool isBalanced(TreeNode* root) { + return balanceness(root) != -1; + } +}; \ No newline at end of file diff --git a/112.txt b/112.txt new file mode 100644 index 0000000..c0c5bf2 --- /dev/null +++ b/112.txt @@ -0,0 +1,31 @@ +Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. +For example: +Given the below binary tree and sum = 22, + + 5 + / \ + 4 8 + / / \ + 11 13 4 + / \ \ + 7 2 1 + +return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + bool hasPathSum(TreeNode* root, int sum) { + if(root == NULL) return false; + if(root->left == NULL && root->right == NULL && sum == root->val) return true; + return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); + } +}; \ No newline at end of file diff --git a/118.txt b/118.txt new file mode 100644 index 0000000..506f441 --- /dev/null +++ b/118.txt @@ -0,0 +1,32 @@ +Given numRows, generate the first numRows of Pascal's triangle. +For example, given numRows = 5, +Return +[ + [1], + [1,1], + [1,2,1], + [1,3,3,1], + [1,4,6,4,1] +] + +class Solution { +public: + vector> generate(int numRows) { + vector> pascal; + pascal.resize(numRows); + for(int i = 1; i <= numRows; i++) + pascal[i - 1].resize(i); + + for(int i = 0; i < numRows; i++) + for(int j = 0; j < i + 1; j++) + { + if(j == 0) pascal[i][j] = 1; + else + if(j == i) pascal[i][j] = 1; + else + pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j]; + } + + return pascal; + } +}; \ No newline at end of file diff --git a/119.txt b/119.txt new file mode 100644 index 0000000..67967bb --- /dev/null +++ b/119.txt @@ -0,0 +1,21 @@ +Given an index k, return the kth row of the Pascal's triangle. + +For example, given k = 3, +Return [1,3,3,1]. + +Note: +Could you optimize your algorithm to use only O(k) extra space? + +// use O(k) extra space +class Solution { +public: + vector getRow(int rowIndex) { + vector pascal(rowIndex + 1, 0); + pascal[0] = 1; + + for(int i = 1; i < rowIndex + 1; i++) + for(int j = i; j >= 1; j--) + pascal[j] += pascal[j - 1]; + return pascal; + } +}; \ No newline at end of file diff --git a/13.txt b/13.txt new file mode 100644 index 0000000..248709c --- /dev/null +++ b/13.txt @@ -0,0 +1,33 @@ +Given a roman numeral, convert it to an integer. + +Input is guaranteed to be within the range from 1 to 3999. + +// the Roman alphabet is listed in the switch statement below +class Solution { +public: + int decode(char c){ + switch(c){ + case 'I': return 1; + case 'V': return 5; + case 'X': return 10; + case 'L': return 50; + case 'C': return 100; + case 'D': return 500; + case 'M': return 1000; + } + } + + int romanToInt(string s) { + int n = 0; + int n1, n2; + for(int i = 0; i < s.size() - 1; i++) + { + n1 = decode(s[i]); + n2 = decode(s[i + 1]); + if(n1 < n2) n -= n1; + else n += n1; + } + n += decode(s[s.size()-1]); + return n; + } +}; \ No newline at end of file diff --git a/136.txt b/136.txt new file mode 100644 index 0000000..2ae00ce --- /dev/null +++ b/136.txt @@ -0,0 +1,14 @@ +//Given an array of integers, every element appears twice except for one. Find that single one. + +//Note: +//Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? + +// A ^ A = 0, 0 ^ A = 0, A ^ B ^ A = B +class Solution { +public: + int singleNumber(vector& nums) { + for(int i = 1; i < nums.size(); i++) + nums[0] = nums[0] ^ nums[i]; + return nums[0]; + } +}; \ No newline at end of file diff --git a/168.txt b/168.txt new file mode 100644 index 0000000..b2ff879 --- /dev/null +++ b/168.txt @@ -0,0 +1,47 @@ +Given a positive integer, return its corresponding column title as appear in an Excel sheet. +For example: + + 1 -> A + 2 -> B + 3 -> C + ... + 26 -> Z + 27 -> AA + 28 -> AB + + +class Solution { +public: + string convertToTitle(int n) { + string result, s_tmp; + char ch_tmp; + int tail = 0; + while(n > 0) + { + tail = n % 26; + if(tail == 0) + { + tail = 26; + result = "Z" + result; + } + else + { + ch_tmp = 'A' - 1 + tail; + s_tmp = ch_tmp; + result = s_tmp + result; + } + n = (n - tail)/26; + } + + /* + while(n){ + n -= 1; + ch_tmp = 'A' + n % 26; + result = ch_tmp + result; + n /= 26; + } + */ + + return result; + } +}; \ No newline at end of file diff --git a/169.txt b/169.txt new file mode 100644 index 0000000..4337795 --- /dev/null +++ b/169.txt @@ -0,0 +1,36 @@ +Given an array of size n, find the majority element. The majority element is the element that appears more than ? n/2 ? times. + +You may assume that the array is non-empty and the majority element always exist in the array. + + +// sort then count +class Solution { +public: + int majorityElement(vector& nums) { + int n = 1; + if(nums.size() == 1) return nums[0]; + sort(nums.begin(),nums.end()); + for(int i = 1; i < nums.size(); i++) + if(nums[i - 1] == nums[i]) + { + n++; + if(n > nums.size()/2) return nums[i]; + } + } +}; + +// use hash map +class Solution { +public: + int majorityElement(vector& nums) { + unordered_map count; + for(int i = 0; i < nums.size(); i++) + { + if(++count[nums[i]] > nums.size()/2) + return nums[i]; + } + } +}; + +//6 Suggested Solutions in C++ with Explanations: +//https://leetcode.com/discuss/42929/6-suggested-solutions-in-c-with-explanations \ No newline at end of file diff --git a/171.txt b/171.txt new file mode 100644 index 0000000..f7381a9 --- /dev/null +++ b/171.txt @@ -0,0 +1,24 @@ +Related to question Excel Sheet Column Title +Given a column title as appear in an Excel sheet, return its corresponding column number. +For example: + A -> 1 + B -> 2 + C -> 3 + ... + Z -> 26 + AA -> 27 + AB -> 28 + + +class Solution { +public: + int titleToNumber(string s) { + int j = 0,n = 0; + for(int i = 0; i < s.size() ; i++) + { + j = s.size() - 1 - i; + n = n + pow(26, i) * (s[j] - 'A' + 1); + } + return n; + } +}; \ No newline at end of file diff --git a/172.txt b/172.txt new file mode 100644 index 0000000..c23609a --- /dev/null +++ b/172.txt @@ -0,0 +1,20 @@ +Given an integer n, return the number of trailing zeroes in n!. + +Note: Your solution should be in logarithmic time complexity. + +// count the number of 5 +class Solution { +public: + int trailingZeroes(int n) { + int count = 0; + int i = n; + + while(i > 1) + { + count += i/5; + i = i/5; + } + + return count; + } +}; \ No newline at end of file diff --git a/191.txt b/191.txt new file mode 100644 index 0000000..c0b2f07 --- /dev/null +++ b/191.txt @@ -0,0 +1,15 @@ +//Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). +//For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should return 3. + +class Solution { +public: + int hammingWeight(uint32_t n) { + int num = 0; + while(n) + { + n = n & (n-1); + num++; + } + return num; + } +}; \ No newline at end of file diff --git a/198.txt b/198.txt new file mode 100644 index 0000000..f84eca3 --- /dev/null +++ b/198.txt @@ -0,0 +1,36 @@ +You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. + +Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. + +class Solution { +public: + int rob(vector& nums) { + int robber[nums.size() + 1][2] = {0}; + for(int i = 1; i <= nums.size(); i++) + { + robber[i][0] = max(robber[i - 1][0], robber[i - 1][1]); // if not rob + robber[i][1] = nums[i - 1] + robber[i - 1][0]; // if rob + } + + return max(robber[nums.size()][0], robber[nums.size()][1]); + } +}; + + +// O(1) space +class Solution { +public: + int rob(vector& nums) { + int rob = 0; + int notrob = 0; + int temp = 0; + for(int i = 0; i < nums.size(); i++) + { + temp = notrob; //temp is used to keep the unmodified notrob + notrob = max(rob, notrob); //if not rob, compare + rob = nums[i] + temp; //if rob, previous house must not rob + } + + return max(rob, notrob); + } +}; \ No newline at end of file diff --git a/202.txt b/202.txt new file mode 100644 index 0000000..cf827b6 --- /dev/null +++ b/202.txt @@ -0,0 +1,57 @@ +Write an algorithm to determine if a number is "happy". + +A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. + +Example: 19 is a happy number + + 12 + 92 = 82 + 82 + 22 = 68 + 62 + 82 = 100 + 12 + 02 + 02 = 1 + +// if the number is not happy,it loops as 4->16->37->58->89->145->42->20->4, +// so we can use a fast and a slow pointer to test if there is a cycle +class Solution { +public: + int digitSquareSum(int n) + { + int sum = 0, tmp; + while(n) + { + tmp = n % 10; + sum += tmp * tmp; + n /= 10; + } + return sum; + } + bool isHappy(int n) { + int slow, fast; + slow = fast = n; + do { + slow = digitSquareSum(slow); + fast = digitSquareSum(digitSquareSum(fast)); + } while(slow != fast); + + if(slow == 1) return true; + else return false; + } +}; + +// now that 4 is unhappy, we have follow code +class Solution { +public: + bool isHappy(int n) { + while (true) { + if (n == 1) { return true; } + if (n == 4) { return false; } + int sum = 0, tmp; + while (n) + { + tmp = n % 10; + sum += tmp * tmp; + n /= 10; + } + n = next; + } + } +}; \ No newline at end of file diff --git a/21.txt b/21.txt new file mode 100644 index 0000000..eeca56b --- /dev/null +++ b/21.txt @@ -0,0 +1,33 @@ +Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + if(l1 == NULL) return l2; + if(l2 == NULL) return l1; + + ListNode *result; + if(l1->val <= l2->val) { result = l1; l1 = l1->next; } + else { result = l2; l2 = l2->next; } + + ListNode *p = result; + while(l1 != NULL && l2 != NULL) + { + if(l1->val <= l2->val) { p->next = l1; l1 = l1->next; } + else { p->next = l2; l2 = l2->next; } + p = p->next; + } + if(l1 != NULL && l2 == NULL) { p->next = l1; } + if(l2 != NULL && l1 == NULL) { p->next = l2; } + + return result; + } +}; \ No newline at end of file diff --git a/217.txt b/217.txt new file mode 100644 index 0000000..c0884be --- /dev/null +++ b/217.txt @@ -0,0 +1,31 @@ +Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. + +//sort and compare, faster +class Solution { +public: + bool containsDuplicate(vector& nums) { + sort(nums.begin(), nums.end()); + for(int i = 1; i < nums.size(); i++) + if(nums[i-1] == nums[i]) + return true; + return false; + } +}; + + +//use hash_set, slower +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_set hash; + vector::iterator it = nums.begin(); + for(; it != nums.end(); it++) + { + if(hash.find(*it) != hash.end()) + return true; + else + hash.insert(*it); + } + return false; + } +}; \ No newline at end of file diff --git a/225.txt b/225.txt new file mode 100644 index 0000000..b4dc827 --- /dev/null +++ b/225.txt @@ -0,0 +1,42 @@ +Implement the following operations of a stack using queues. + + push(x) -- Push element x onto stack. + pop() -- Removes the element on top of the stack. + top() -- Get the top element. + empty() -- Return whether the stack is empty. + +Notes: + + You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. + Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. + You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). + +// queue front is the stack top +class Stack { + queue q; +public: + // Push element x onto stack. + void push(int x) { + q.push(x); + for(int i = 0; i < q.size() -1; i++) + { + q.push(q.front()); + q.pop(); + } + } + + // Removes the element on top of the stack. + void pop() { + q.pop(); + } + + // Get the top element. + int top() { + return q.front(); + } + + // Return whether the stack is empty. + bool empty() { + return q.empty(); + } +}; \ No newline at end of file diff --git a/226.txt b/226.txt new file mode 100644 index 0000000..5f47b50 --- /dev/null +++ b/226.txt @@ -0,0 +1,38 @@ +Invert a binary tree. + + 4 + / \ + 2 7 + / \ / \ +1 3 6 9 + +to + + 4 + / \ + 7 2 + / \ / \ +9 6 3 1 + + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if(root) + { + swap(root->left, root->right); + invertTree(root->left); + invertTree(root->right); + } + return root; + } +}; \ No newline at end of file diff --git a/231.txt b/231.txt new file mode 100644 index 0000000..75732e9 --- /dev/null +++ b/231.txt @@ -0,0 +1,24 @@ +Given an integer, write a function to determine if it is a power of two. + +class Solution { +public: + bool isPowerOfTwo(int n) { + if(n <= 0) return false; + while(n) + { + if(n == 1) return true; + if(n % 2 != 0) return false; + + n = n/2; + } + } +}; + +// power of 2 means only have 1 bit of "1" +class Solution { +public: + bool isPowerOfTwo(int n) { + if(n <= 0) return false; + return !(n & (n - 1)); + } +}; \ No newline at end of file diff --git a/232.txt b/232.txt new file mode 100644 index 0000000..41723cb --- /dev/null +++ b/232.txt @@ -0,0 +1,64 @@ +Implement the following operations of a queue using stacks. + + push(x) -- Push element x to the back of queue. + pop() -- Removes the element from in front of queue. + peek() -- Get the front element. + empty() -- Return whether the queue is empty. + +Notes: + + You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. + Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. + You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). + + +class Queue { + stack stack1, stack2; +public: + // Push element x to the back of queue. + void push(int x) { + stack1.push(x); + } + + // Removes the element from in front of queue. + void pop(void) { + int n; + while(!stack1.empty()) + { + n = stack1.top(); + stack1.pop(); + stack2.push(n); + } + stack2.pop(); + while(!stack2.empty()) + { + n = stack2.top(); + stack2.pop(); + stack1.push(n); + } + } + + // Get the front element. + int peek(void) { + int m,n; + while(!stack1.empty()) + { + n = stack1.top(); + stack1.pop(); + stack2.push(n); + } + m = stack2.top(); + while(!stack2.empty()) + { + n = stack2.top(); + stack2.pop(); + stack1.push(n); + } + return m; + } + + // Return whether the queue is empty. + bool empty(void) { + return stack1.empty() && stack2.empty(); + } +}; \ No newline at end of file diff --git a/235.txt b/235.txt new file mode 100644 index 0000000..4dfe498 --- /dev/null +++ b/235.txt @@ -0,0 +1,33 @@ +//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)." + _______6______ + / \ + ___2__ ___8__ + / \ / \ + 0 _4 7 9 + / \ + 3 5 +//For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if(p->val == root->val || q->val == root->val + || (p->val < root->val && q->val > root->val) || (p->val > root->val && q->val < root->val)) + return root; + else + { + if(p->val < root->val && q->val < root->val) return lowestCommonAncestor(root->left, p, q); + if(p->val > root->val && q->val > root->val) return lowestCommonAncestor(root->right, p, q); + } + } +}; \ No newline at end of file diff --git a/237.txt b/237.txt new file mode 100644 index 0000000..36a98bc --- /dev/null +++ b/237.txt @@ -0,0 +1,23 @@ +//Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. +//Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ + + // can't get the head node, so implemented by deleting the next node +class Solution { +public: + void deleteNode(ListNode* node) { + //node->val = node->next->val; + //node->next = node->next->next; + auto d_node = node->next; + *node = *node->next; + delete d_node; + } +}; \ No newline at end of file diff --git a/242.txt b/242.txt new file mode 100644 index 0000000..56d9a25 --- /dev/null +++ b/242.txt @@ -0,0 +1,18 @@ +Given two strings s and t, write a function to determine if t is an anagram of s. +For example, +s = "anagram", t = "nagaram", return true. +s = "rat", t = "car", return false. +Note: +You may assume the string contains only lowercase alphabets. + +class Solution { +public: + bool isAnagram(string s, string t) { + unordered_map hash_s, hash_t; + for(int i = 0; i < s.size(); i++) + hash_s[s[i]]++; + for(int i = 0; i < t.size(); i++) + hash_t[t[i]]++; + return hash_s == hash_t; + } +}; \ No newline at end of file diff --git a/258.txt b/258.txt new file mode 100644 index 0000000..73cfd02 --- /dev/null +++ b/258.txt @@ -0,0 +1,48 @@ +//Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. +//For example: +//Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. +//Follow up: +//Could you do it without any loop/recursion in O(1) runtime? +//Hint: +// A naive implementation of the above process is trivial. Could you come up with other methods? +// What are all the possible results? +// How do they occur, periodically or randomly? + +// not the best one +class Solution { +public: + int addDigits(int num) { + if(num < 10) return num; + while(num >= 10) + num = num/10 + num % 10; + return num; + } +}; + +/* +The problem, widely known as digit root problem, has a congruence formula: +https://en.wikipedia.org/wiki/Digital_root#Congruence_formula + +For base b (decimal case b = 10), the digit root of an integer is: + dr(n) = 0 if n == 0 + dr(n) = (b-1) if n != 0 and n % (b-1) == 0 + dr(n) = n mod (b-1) if n % (b-1) != 0 +or + dr(n) = 1 + (n - 1) % 9 + +Note here, when n = 0, since (n - 1) % 9 = -1, the return value is zero (correct). +From the formula, we can find that the result of this problem is immanently periodic, with period (b-1). +Output sequence for decimals (b = 10): + +~input: 0 1 2 3 4 ... +output: 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 .... + +Henceforth, we can write the following code, whose time and space complexities are both O(1). +*/ + +class Solution { +public: + int addDigits(int num) { + return 1 + (num - 1) % 9; + } +}; \ No newline at end of file diff --git a/26.txt b/26.txt new file mode 100644 index 0000000..ba82c7c --- /dev/null +++ b/26.txt @@ -0,0 +1,22 @@ +Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. +Do not allocate extra space for another array, you must do this in place with constant memory. +For example, +Given input array nums = [1,1,2], +Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. + +class Solution { +public: + int removeDuplicates(vector& nums) { + if(nums.size() < 2) return nums.size(); + int count = 1; + for(int i = 1; i < nums.size(); i++) + { + if(nums[i - 1] != nums[i]) + { + nums[count] = nums[i]; + count++; + } + } + return count; + } +}; \ No newline at end of file diff --git a/263.txt b/263.txt new file mode 100644 index 0000000..a713737 --- /dev/null +++ b/263.txt @@ -0,0 +1,17 @@ +Write a program to check whether a given number is an ugly number. + +Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. + +Note that 1 is typically treated as an ugly number. + +class Solution { +public: + bool isUgly(int num) { + if(num <= 0) return false; + if(num == 1) return true; + while(num % 2 == 0) num /= 2; + while(num % 3 == 0) num /= 3; + while(num % 5 == 0) num /= 5; + return num == 1; + } +}; \ No newline at end of file diff --git a/27.txt b/27.txt new file mode 100644 index 0000000..ce690ef --- /dev/null +++ b/27.txt @@ -0,0 +1,33 @@ +Given an array and a value, remove all instances of that value in place and return the new length. + +The order of elements can be changed. It doesn't matter what you leave beyond the new length. + +// use "erase" +class Solution { +public: + int removeElement(vector& nums, int val) { + vector::iterator it; + for(it = nums.begin(); it != nums.end();) + if(*it == val) + it = nums.erase(it); + else it++; + return nums.size(); + } +}; + +// use the last element to cover the value +class Solution { +public: + int removeElement(vector& nums, int val) { + for(int i = 0; i < nums.size(); i++) + { + if(nums[i] == val) + { + nums[i] = nums[nums.size() - 1]; + nums.pop_back(); + i--; + } + } + return nums.size(); + } +}; \ No newline at end of file diff --git a/66.txt b/66.txt new file mode 100644 index 0000000..0804496 --- /dev/null +++ b/66.txt @@ -0,0 +1,20 @@ +Given a non-negative number represented as an array of digits, plus one to the number. +The digits are stored such that the most significant digit is at the head of the list. + +class Solution { +public: + vector plusOne(vector& digits) { + int flag = 0; + for(int i = digits.size() - 1; i >=0; i--) + { + if(i == digits.size() -1) digits[i]++; + if(flag == 1) digits[i]++; + + flag = digits[i]/10; + digits[i] = digits[i] % 10; + } + if(flag == 1) + digits.insert(digits.begin(),1); + return digits; + } +}; \ No newline at end of file diff --git a/70.txt b/70.txt new file mode 100644 index 0000000..5f0b5c7 --- /dev/null +++ b/70.txt @@ -0,0 +1,22 @@ +You are climbing a stair case. It takes n steps to reach to the top. + +Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? + +// a Fibonacci problem, n1 means take 1 step and n2 means take 2 step +// F(n) = F(n - 1) + F(n - 2) +class Solution { +public: + int climbStairs(int n) { + if(n <= 0) return 0; + if(n == 1) return 1; + if(n == 2) return 2; + int n1 = 1, n2 = 2, count = 0; + for(int i = 2; i < n; i++) + { + count = n1 + n2; + n1 = n2; + n2 = count; + } + return count; + } +}; \ No newline at end of file diff --git a/83.txt b/83.txt new file mode 100644 index 0000000..8121f2b --- /dev/null +++ b/83.txt @@ -0,0 +1,31 @@ +Given a sorted linked list, delete all duplicates such that each element appear only once. +For example, +Given 1->1->2, return 1->2. +Given 1->1->2->3->3, return 1->2->3. + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode *cur = head; + if(cur != NULL) + { + while(cur->next != NULL) + { + if(cur->val == cur->next->val) + cur->next = cur->next->next; + else + cur = cur->next; + } + return head; + } + return head; + } +}; \ No newline at end of file diff --git a/Binary Tree Level Order Traversal II.txt b/Binary Tree Level Order Traversal II.txt new file mode 100644 index 0000000..e966ae4 --- /dev/null +++ b/Binary Tree Level Order Traversal II.txt @@ -0,0 +1,58 @@ +Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). + +For example: +Given binary tree {3,9,20,#,#,15,7}, + + 3 + / \ + 9 20 + / \ + 15 7 + +return its bottom-up level order traversal as: + +[ + [15,7], + [9,20], + [3] +] + + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + vector> levelOrderBottom(TreeNode* root) { + if(!root) return {}; + + vector> result; + vector row; + queue q; + q.push(root); + int count = 1; + + while(!q.empty()) + { + if(q.front()->left != NULL) q.push(q.front()->left); + if(q.front()->right != NULL) q.push(q.front()->right); + row.push_back(q.front()->val); + q.pop(); + count--; + if(count == 0) + { + result.insert(result.begin(), row); + row.clear(); + count = q.size(); + } + } + + return result; + } +}; \ No newline at end of file diff --git a/Binary Tree Level Order Traversal.txt b/Binary Tree Level Order Traversal.txt new file mode 100644 index 0000000..0733eb7 --- /dev/null +++ b/Binary Tree Level Order Traversal.txt @@ -0,0 +1,56 @@ +Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). +For example: +Given binary tree {3,9,20,#,#,15,7}, + + 3 + / \ + 9 20 + / \ + 15 7 + +return its level order traversal as: + +[ + [3], + [9,20], + [15,7] +] + + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + if(!root) return {}; + vector> result; + vector row; + queue q; + q.push(root); + int count = 1; + + while(!q.empty()) + { + if(q.front()->left) q.push(q.front()->left); + if(q.front()->right) q.push(q.front()->right); + row.push_back(q.front()->val); + q.pop(); + count--; + if(count == 0) + { + result.push_back(row); + row.clear(); + count = q.size(); + } + } + + return result; + } +}; \ No newline at end of file diff --git a/Contains Duplicate II.txt b/Contains Duplicate II.txt new file mode 100644 index 0000000..94db1a5 --- /dev/null +++ b/Contains Duplicate II.txt @@ -0,0 +1,38 @@ +Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. + +// unordered_map +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) { + unordered_map hash_map; + for(int i = 0; i < nums.size(); i++) + { + if(hash_map.find(nums[i]) != hash_map.end() && (i - hash_map[nums[i]]) <= k) + return true; + else + hash_map[nums[i]] = i; + } + return false; + } +}; + +// unordered_set and sliding window +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) + { + unordered_set s; + + if (k <= 0) return false; + if (k >= nums.size()) k = nums.size() - 1; + + for (int i = 0; i < nums.size(); i++) + { + if (i > k) s.erase(nums[i - k - 1]); + if (s.find(nums[i]) != s.end()) return true; + s.insert(nums[i]); + } + + return false; + } +}; \ No newline at end of file diff --git a/Intersection of Two Linked Lists.txt b/Intersection of Two Linked Lists.txt new file mode 100644 index 0000000..f6ea6d2 --- /dev/null +++ b/Intersection of Two Linked Lists.txt @@ -0,0 +1,55 @@ +Write a program to find the node at which the intersection of two singly linked lists begins. + +For example, the following two linked lists: + +A: a1 ¡ú a2 + ¨K + c1 ¡ú c2 ¡ú c3 + ¨J +B: b1 ¡ú b2 ¡ú b3 + +begin to intersect at node c1. + +Notes: + + If the two linked lists have no intersection at all, return null. + The linked lists must retain their original structure after the function returns. + You may assume there are no cycles anywhere in the entire linked structure. + Your code should preferably run in O(n) time and use only O(1) memory. + + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + if(headA == NULL || headB == NULL) return NULL; + + ListNode *pa = headA, *pb = headB; + int len_a = 0, len_b = 0; + int diff = 0; + while(pa){++len_a; pa = pa->next;} + while(pb){++len_b; pb = pb->next;} + diff = abs(len_a - len_b); + pa = headA; + pb = headB; + + while(pa && pb){ + if(len_a > len_b) + while(diff){--diff; pa = pa->next;} + else + while(diff){--diff; pb = pb->next;} + while(pa != pb){ + pa = pa->next; + pb = pb->next; + } + return pa; + } + } +}; \ No newline at end of file diff --git a/Length of Last Word.txt b/Length of Last Word.txt new file mode 100644 index 0000000..7d3d1a9 --- /dev/null +++ b/Length of Last Word.txt @@ -0,0 +1,28 @@ +Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. + +If the last word does not exist, return 0. + +Note: A word is defined as a character sequence consists of non-space characters only. + +For example, +Given s = "Hello World", +return 5. + + +class Solution { +public: + int lengthOfLastWord(string s) { + int len = s.size(); + if(len == 0) return 0; + int i = len - 1; + int n = 0; + while(s[i] == ' ') + i--; + while(s[i] != ' ' && i >= 0) + { + n++; + i--; + } + return n; + } +}; \ No newline at end of file diff --git a/Longest Common Prefix.txt b/Longest Common Prefix.txt new file mode 100644 index 0000000..dd7b8ea --- /dev/null +++ b/Longest Common Prefix.txt @@ -0,0 +1,32 @@ +Write a function to find the longest common prefix string amongst an array of strings. + + +class Solution { +public: + string longestCommonPrefix(vector& strs) { + int len = strs.size(); + if(len == 0) return ""; + if(len == 0) return strs[0]; + + string pre = ""; + char tmp; + + int min = strs[0].size(); + for(int i = 1; i < len; i++) + if(strs[i].size() < min) + min = strs[i].size(); + + for(int i = 0; i < min; i++) + { + tmp = strs[0][i]; + for(int j = 0; j < len; j++) + { + if(strs[j][i] != tmp) + return pre; + } + pre = pre + tmp; + } + + return pre; + } +}; \ No newline at end of file diff --git a/Merge Sorted Array.txt b/Merge Sorted Array.txt new file mode 100644 index 0000000..e227e54 --- /dev/null +++ b/Merge Sorted Array.txt @@ -0,0 +1,31 @@ +Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. + +Note: +You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. + +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + vector result; + int i = 0, j = 0; + while(i < m && j < n){ + if(nums1[i] <= nums2[j]){ + result.push_back(nums1[i]); + ++i; + } + else{ + result.push_back(nums2[j]); + ++j; + } + } + + if(i < m) + for(; i < m; ++i) + result.push_back(nums1[i]); + if(j < n) + for(; j < n; ++j) + result.push_back(nums2[j]); + + nums1 = result; + } +}; \ No newline at end of file diff --git a/Minimum Depth of Binary Tree.txt b/Minimum Depth of Binary Tree.txt new file mode 100644 index 0000000..8bc01e0 --- /dev/null +++ b/Minimum Depth of Binary Tree.txt @@ -0,0 +1,22 @@ +Given a binary tree, find its minimum depth. + +The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int minDepth(TreeNode* root) { + if(root == NULL) return 0; + if(root->left == NULL) return 1 + minDepth(root->right); + if(root->right == NULL) return 1 + minDepth(root->left); + return 1 + min(minDepth(root->left), minDepth(root->right)); + } +}; \ No newline at end of file diff --git a/Move Zeroes.txt b/Move Zeroes.txt new file mode 100644 index 0000000..7eb9925 --- /dev/null +++ b/Move Zeroes.txt @@ -0,0 +1,36 @@ +Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. + +For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. + +Note: + + You must do this in-place without making a copy of the array. + Minimize the total number of operations. + +Credits: +Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. + + +class Solution { +public: + void moveZeroes(vector& nums) { + int len = nums.size(); + if(len == 1) return; + int n = 0; + for(int i = 0; i < len; i++) + { + if(nums[i] != 0) + { + nums[n] = nums[i]; + n++; + } + } + int diff = len - n; + while(diff) + { + nums[n] = 0; + n++; + diff--; + } + } +}; \ No newline at end of file diff --git a/Palindrome Number.txt b/Palindrome Number.txt new file mode 100644 index 0000000..1d49fbe --- /dev/null +++ b/Palindrome Number.txt @@ -0,0 +1,19 @@ +Determine whether an integer is a palindrome. Do this without extra space. + +class Solution { +public: + bool isPalindrome(int x) { + if(x < 0) return false; + int rev = 0; + int tmp = x; + while(x != 0) + { + rev = rev * 10 + x % 10; + x = x / 10; + } + if(rev == tmp) + return true; + else + return false; + } +}; \ No newline at end of file diff --git a/Remove Linked List Elements.txt b/Remove Linked List Elements.txt new file mode 100644 index 0000000..12e95c3 --- /dev/null +++ b/Remove Linked List Elements.txt @@ -0,0 +1,39 @@ +Remove all elements from a linked list of integers that have value val. + +Example +Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 +Return: 1 --> 2 --> 3 --> 4 --> 5 + + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + if(head == nullptr) return nullptr; + + ListNode *newHead, *p, *tmp; + newHead->next = head; + p = newHead; + + while(p->next != nullptr) + { + if(p->next->val == val) + { + tmp = p->next; + p->next = p->next->next; + tmp = nullptr; + } + else + p = p->next; + } + + return newHead->next; + } +}; \ No newline at end of file diff --git a/Remove Nth Node From End of List.txt b/Remove Nth Node From End of List.txt new file mode 100644 index 0000000..fd6ded1 --- /dev/null +++ b/Remove Nth Node From End of List.txt @@ -0,0 +1,49 @@ +Given a linked list, remove the nth node from the end of list and return its head. + +For example, + + Given linked list: 1->2->3->4->5, and n = 2. + + After removing the second node from the end, the linked list becomes 1->2->3->5. + +Note: +Given n will always be valid. +Try to do this in one pass. + + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode *newhead = new ListNode(0); + newhead->next = head; + ListNode *fast, *slow; + fast = newhead; + slow = newhead; + + while(n) + { + fast = fast->next; + n--; + } + + while(fast->next != nullptr) + { + fast = fast->next; + slow = slow->next; + } + + ListNode *tmp = slow->next; + slow->next = tmp->next; + tmp = nullptr; + + return newhead->next; + } +}; \ No newline at end of file diff --git a/Reverse Bits.txt b/Reverse Bits.txt new file mode 100644 index 0000000..1ae7bd8 --- /dev/null +++ b/Reverse Bits.txt @@ -0,0 +1,36 @@ +Reverse bits of a given 32 bits unsigned integer. + +For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). + +Follow up: +If this function is called many times, how would you optimize it? + +Related problem: Reverse Integer + + +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t result = 0; + + for(int i = 0; i < 32; ++i){ + if((n & 0x80000000) == 0x80000000) + result += pow(2,i); + n = n << 1; + } + + return result; + } +}; + +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t result = 0; + + for(int i = 0; i < 32; ++i) + result = (result << 1) + (n >> i & 1); + + return result; + } +}; \ No newline at end of file diff --git a/Reverse Linked List.txt b/Reverse Linked List.txt new file mode 100644 index 0000000..a620917 --- /dev/null +++ b/Reverse Linked List.txt @@ -0,0 +1,33 @@ +Reverse a singly linked list. + +click to show more hints. +Hint: +A linked list can be reversed either iteratively or recursively. Could you implement both? + + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if(head == NULL || head->next == NULL) return head; + ListNode *p, *pre; + pre = NULL; + while(head->next != NULL) + { + p = head; + head = head->next; + p->next = pre; + pre = p; + } + head->next = p; + + return head; + } +}; \ No newline at end of file diff --git a/Valid Parentheses.txt b/Valid Parentheses.txt new file mode 100644 index 0000000..9899685 --- /dev/null +++ b/Valid Parentheses.txt @@ -0,0 +1,37 @@ +Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. + +The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. + + +class Solution { +public: + bool isValid(string s) { + stack ss; + if(s.size() % 2 != 0) return false; + for(int i = 0; i < s.size(); i++) + { + if(s[i] ==')') + { + if(!ss.empty() && ss.top() == '(') ss.pop(); + else return false; + } + else + if(!ss.empty() && s[i] ==']') + { + if(ss.top() == '[') ss.pop(); + else return false; + } + else + if(!ss.empty() && s[i] =='}') + { + if(ss.top() == '{') ss.pop(); + else return false; + } + else + ss.push(s[i]); + } + + if(ss.empty()) return true; + else return false; + } +}; \ No newline at end of file diff --git a/Valid Sudoku.txt b/Valid Sudoku.txt new file mode 100644 index 0000000..dffaa95 --- /dev/null +++ b/Valid Sudoku.txt @@ -0,0 +1,59 @@ +Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. + +The Sudoku board could be partially filled, where empty cells are filled with the character '.' + +A partially filled sudoku which is valid. + +Note: +A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. + + +class Solution { +public: + bool isValidSudoku(vector>& board) { + int row[9], col[9]; + + for(int i = 0; i < 9; i++) + { + memset(row, 0 , sizeof(int) * 9); + memset(col, 0 , sizeof(int) * 9); + for(int j = 0; j < 9; j++) + { + if(board[i][j] != '.') + { + if(row[board[i][j]-'1']) + return false; + else + row[board[i][j]-'1']++; + } + + if(board[j][i] != '.') + { + if(col[board[j][i]-'1']) + return false; + else + col[board[j][i]-'1']++; + } + } + } + + for(int i = 0; i < 9; i+=3) + for(int j = 0; j < 9; j+=3) + { + memset(row, 0, sizeof(int) * 9); + for(int m = 0; m < 3; m++) + for(int n = 0; n < 3; n++) + { + if(board[i+m][j+n] != '.') + { + if(row[board[i+m][j+n]-'1']) + return false; + else + row[board[i+m][j+n]-'1']++; + } + } + } + + return true; + } +}; \ No newline at end of file diff --git a/btsearch.cpp b/btsearch.cpp deleted file mode 100644 index f908d6f..0000000 --- a/btsearch.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include -#include -using namespace std; - -int index = 0; - -typedef struct Node -{ - char data; - struct Node *lchild; - struct Node *rchild; -}* Tree; - -void treeConstructor(Tree &node, char data[]) -{ - char e = data[index++]; - if(e == '#') - node = nullptr; - else - { - node = new Node; - node->data = e; - treeConstructor(node->lchild, data); - treeConstructor(node->rchild, data); - } -} - -void DFS(Tree root) -{ - stack nodeStack; - nodeStack.push(root); - Node *node; - while(!nodeStack.empty()) - { - node = nodeStack.top(); - cout << node->data; - nodeStack.pop(); - if(node->rchild) - nodeStack.push(node->rchild); - if(node->lchild) - nodeStack.push(node->lchild); - } -} - -void BFS(Tree root) -{ - queuenodeQueue; - nodeQueue.push(root); - Node *node; - while(!nodeQueue.empty()) - { - node = nodeQueue.front(); - cout << node->data; - nodeQueue.pop(); - if(node->lchild) - nodeQueue.push(node->lchild); - if(node->rchild) - nodeQueue.push(node->rchild); - } -} - -int main() -{ - char data[16] = {'A', 'B', 'D', '#', '#', 'E', '#', '#', 'C', 'F', '#', '#', 'G', '#', '#', '\0'}; - Tree root; - treeConstructor(root, data); - cout << "DFS: "; - DFS(root); - cout << endl; - cout << "DFS: "; - BFS(root); - cout << endl; - - return 0; -} diff --git a/graphSearch.cpp b/graphSearch.cpp deleted file mode 100644 index ff144a0..0000000 --- a/graphSearch.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include -#include -#include -using namespace std; - -const int vnum = 5; -int visited[vnum]; - -struct Graph -{ - int vertex[vnum]; - int arc[vnum][vnum]; -}; - -void CreatGraph(Graph &G, int data[], int maxtrix[][vnum]) -{ - for(int i = 0; i < vnum; i++) - G.vertex[i] = data[i]; - for(int i = 0; i < vnum; i++) - for(int j = 0; j < vnum; j++) - G.arc[i][j] = maxtrix[i][j]; -} - -void DFS(Graph *G, int v) -{ - if(!visited[v]) - { - cout << G->vertex[v]; - visited[v] = 1; - } - for(int i = 0; i < vnum; i++) - if(G->arc[v][i] && visited[i] != 1) - DFS(G, i); -} - -void BFS(Graph *G, int v) -{ - int f; - queue q; - if(!visited[v]) - { - cout << G->vertex[v]; - visited[v] = 1; - q.push(v); - } - while(!q.empty()) - { - f = q.front(); - q.pop(); - for(int i = 0; i < vnum; i++) - if(G->arc[f][i] && visited[i] != 1) - { - cout << G->vertex[i]; - visited[i] = 1; - q.push(i); - } - } -} - -int main() -{ - Graph *G = new Graph; - - int data[vnum] = {1, 2, 3, 4, 5}; - int arcMatrix[vnum][vnum] = - { - {0, 1, 1, 0, 0}, - {1, 0, 0, 1, 0}, - {1, 0, 0, 1, 1}, - {0, 1, 1, 0, 1}, - {0, 0, 1, 1, 0}, - }; - - CreatGraph(*G, data, arcMatrix); - cout << "vertex: "; - for(int i = 0; i < vnum; i++) - cout << G->vertex[i]; - cout << endl << "arc: " << endl; - for(int i = 0; i < vnum; i++) - { - cout << " "; - for(int j = 0; j < vnum; j++) - cout << G->arc[i][j]; - cout << endl; - } - cout << endl; - - cout << "DFS: " << endl; - DFS(G, 0); - cout << endl; - - memset(visited, 0, sizeof(visited)); - - cout << "BFS: " << endl; - BFS(G, 0); - cout << endl; - - return 0; -}