Sorting algorithm - Binary Tree and stack

1. binary tree:

     (1) maximum depth: recursion, the maximum depth is equal to the maximum value of the left subtree between the maximum depth and the maximum depth of the right subtree + 1.

     (2) Minimum Depth: between the minimum value + minimum depth recursion, when the left and right subtrees are not empty, the minimum depth is equal to the left and the right subtree of the subtrees, when one side is empty subtree, the minimum depth +1 minimum equal to the maximum depth between the minimum depth and the right subtree left subtree.       

     (3) Symmetric Tree: determining whether the tree is a tree of images:

            Recursively determining whether two trees mirror, conditions: the same value as the mirror right subtree root, left subtree of A and B, the mirror left subtree right subtree of A and B.

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
     if (root == NULL) return true;
     return checkSymmetric(root->left, root->right);
    }
private: bool checkSymmetric(TreeNode* p1, TreeNode *p2) { if (p1 == NULL && p2 == NULL) return true; if (p1 == NULL || p2 == NULL) return false; if (p1->val == p2->val) { return checkSymmetric(p1->left, p2->right) && checkSymmetric(p1->right, p2->left); } return false; }

      (4) from the first sequence and array configuration binary sequence:

             The first element of the array is the root preorder, inorder to find the root array, divided into left and right sub-tree sub-tree recursively.            

/**
 * 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* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int ps = 0;
        int pe = preorder.size() - 1;
        int is = 0; int ie = inorder.size() - 1; return construct(preorder, inorder, ps, pe, is, ie); } private: TreeNode* construct(vector<int>& preorder, vector<int> inorder, int ps, int pe, int is ,int ie){ if (ps > pe) { return nullptr; } TreeNode* root = new TreeNode(preorder[ps]); int pos; for (int i =is; i <=ie; i++) { if (inorder[i] == root->val){ pos = i; break; } } root->left = construct(preorder, inorder, ps + 1, ps + pos - is, is, pos - 1); root->right = construct(preorder, inorder, ps + pos -is + 1, pe, pos+1, ie); return root; } };

      (5) an ordered array structure binary tree search

   It is the median BST root node array. First build root, recursively construct left subtree and right subtree. If the ordered list into a binary tree structure, each intermediate node is found O (N), and with the speed of a pointer, a step, a take two steps.       

class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        int len = nums.size();
        if (len == 0) return NULL;
        return constructTree(nums, 0, len-1); } private: TreeNode* constructTree(const vector<int> &nums, int s, int e) { if (s > e ) return NULL; int mid = (s + e) / 2; TreeNode* root = new TreeNode(nums[mid]); root->left = constructTree(nums, s, mid - 1); root->right = constructTree(nums, mid + 1, e); return root; } };

    Upgraded sorted linked list, with a global listnode pointer list is ordered binary tree traversal sequence results, performed in order to establish a binary tree.

class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if (head == NULL) return NULL;
        ListNode *p = head;
        int n = 0; while(p->next !=NULL) { p = p->next; n++; } node = head; return constructMidTree(head, 0, n); } private: ListNode* node; TreeNode* constructMidTree(ListNode* head, int s, int e){ if (s > e ) return NULL; int mid = (s + e) / 2; TreeNode* left = constructMidTree(head, s, mid-1); TreeNode* root = new TreeNode(node->val); node = node->next; root->left = left; root->right = constructMidTree(head, mid+1, e); return root; } };

 

2. Stack

 (1) decoded string 

  举例:s = "3[a]2[bc]", return "aaabcbc", s = "3[a2[c]]", return "accaccacc", s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

     Using a stack <vector <int >> s1 maintain the number of occurrences, using a stack <vector <string >> s2 maintain the current level of string after decoding, wife of a [] represents the next level. Character encountered divided into three cases, the digital s1 stack (continuous numeric character is a digit), [the new hierarchy into s2, append characters to the top of the stack STR,] the decoding time a reduced level, s1. pop (). s2.pop (), after expanding updates s2.top ().

   

    string decodeString(string s) {
        int len = s.size();
        if (len == 0) return s;
        int i = 0;
        stack<int> helper_count;
        stack<string> helper_string; helper_string.push(""); while (i < len) { if (s[i] >= '1' && s[i] <= '9') { int count = 0; while(s[i] !='[') { count = 10 * count + int(s[i] - '0'); i++; } helper_count.push(count); helper_string.push(""); i++; } else if ((s[i] >= 'a' && s[i] <= 'z') ||(s[i] >= 'A' && s[i] <= 'Z')) { string top = helper_string.top(); helper_string.pop(); helper_string.push(top + s[i]); i++; } else { int top_count = helper_count.top(); helper_count.pop(); string top_str = helper_string.top(); helper_string.pop(); string upt_str; for (int c=0; c<top_count; c++) { upt_str += top_str; } upt_str = helper_string.top() + upt_str; helper_string.pop(); helper_string.push(upt_str); i++; } } return helper_string.top(); }

 

(2) subsequent expression calculation formula

           3

         /     \       

       +      *

     /    \

     2    1      

Example 1:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

  With a stack <int> maintenance of digital, the digital push met met two symbols out from the top of the stack elements, calculate (top2 * top1), the results stack.

  Review: C ++ function: string digital-to-digital: atoi (string.c_str ())

// string transfer * char: 
 String = STR "World"; 
const char * P = str.c_str (); 
// char * transfected String 
String S; 
char * P = "Hello"; // direct assignment 
s = p;

 

   

public:
    int evalRPN(vector<string>& tokens) {
       int len = tokens.size();
       stack<int> helper;
       for (int i = 0; i < len; i++) {
           if (!isSymbol(tokens[i])) { helper.push(atoi(tokens[i].c_str())); } else { int top1 = helper.top(); helper.pop(); int top2 = helper.top(); helper.pop(); int new_top = compute(top2, top1, tokens[i]); helper.push(new_top); } } return helper.top(); } private: int compute(int x, int y, string symbol) { if (symbol == "+") return x + y; else if (symbol == "-") return x - y; else if (symbol == "*") return x * y; else return x / y; } bool isSymbol(string a) { if (a == "+" || a == "-" || a== "*" || a == "/"){ return true; } return false; }

 

(3) Statistics chemical elements

INPUT: 
Formula = "of Mg (OH) 2" 
the Output: "H2MgO2" 
Explanation: 
of The COUNT of Elements are { 'H': 2, 'of Mg':. 1, 'O': 2}. 
With a stack maintenance number, a stack maintenance stack <map <string, int >> , when traversing look into several cases, character, it is determined there is no follow-up figures, updated top element, left parenthesis is the new level, a level minus the closing parenthesis.
class Solution {
public:
    string countOfAtoms(string formula) {
        int len = formula.size();
        stack<map<string, int>> helper;
        map<string, int> init; helper.push(init); int i = 0; while (i < len) { if (formula[i] >= 'A' && formula[i] <= 'Z'){ string cur = ""; cur = formula[i++]; cout << cur; while(i < len && formula[i] >= 'a'&& formula[i] <= 'z'){ cur += formula[i++]; } int count = 1; if (i < len && isnumber(formula[i])) { count = 0; while(i< len && isnumber(formula[i])){ count = count * 10 + (formula[i] - '0'); i++; } } // update map top element  updateTop(helper, make_pair(cur, count)); } else if (formula[i] == '(') { map<string, int> temp; helper.push(temp); i++; } else if (formula[i] == ')') { i++; int count = 1; if (i < len && isnumber(formula[i])) { count = 0; while(i < len && isnumber(formula[i])){ count = count * 10 + (formula[i] - '0'); i++; } } mergeTop(helper, count); // merge top1 * count + top2 to the new top  } } map<string, int>::iterator iter; map<string, int> final = helper.top(); string result=""; for (iter = final.begin(); iter != final.end();traveling ++ ) {result + = iter->first; if (iter->second > 1) result += to_string(iter->second); } return result; } private: bool isnumber(char s) { if (s >= '0' && s <= '9') return true; return false; } void updateTop(stack<map<string, int>> &helper, const pair<string, int>p) { map<string, int> &top_map = helper.top(); //map<string, int>::iterator iter = top_map.find(p.first); top_map[p.first] += p.second; return; } void mergeTop(stack<map<string, int>>& helper, const int count) { map<string, int> top1_map = helper.top(); helper.pop(); map<string, int> &top2_map = helper.top(); map<string, int>::iterator iter; for (iter = top1_map.begin(); iter != top1_map.end(); iter++) { //map<string, int>::iterator iter_find = top2_map.find(iter->first); top2_map[iter->first] += iter->second * count; } return; } };

 

 

Review map:

Map <String, int> the myMap; 
Map <String, int> :: Iterator ITER; 
String Test 

// find whether there is key: = a.find ITER (Test); IF (ITER myMap.end == ()); 

/ / add new Key:  the myMap [Test] = 0; // if there is automatically initialized to 0.  mapStudent.insert (pair <String, String> ( "R000", "student_zero" )); // iterator = mapStudent.find delete iter ( "R123" ); mapStudent.erase (iter); // delete keyword int n = mapStudent.erase ( "r123" ); // If you delete returns 1, otherwise it returns 0 // deleted by the iterator range: the entire map emptied mapStudent.erase (mapStudent.begin (), mapStudent.end ( )); // equivalent to mapStudent.clear ()

 

 

        

Guess you like

Origin www.cnblogs.com/cookcoder-mr/p/11080068.html