一堆c++二叉樹記錄

#if 1
#include<iostream>
#include <queue>
#include <stack>
#include <string.h>
#include <stdio.h>
using namespace std;
 
struct BianrySearchThree{
     int data;
     BianrySearchThree* lChild;
     BianrySearchThree* rChild;
    
     BianrySearchThree(int value){
        data = value;
        lChild = NULL;
        rChild = NULL;
    }
    BianrySearchThree(){
        
    }
};
 
/*建立一個二叉搜索樹(也就是一顆排序好了的樹)
  注意這裏是“  BianrySearchThree* &root不是BianrySearchThree* root ” */
void Insert(BianrySearchThree* &root, int value){
     if(NULL == root){
         root = new BianrySearchThree(value);
         root->data = value;
         root->lChild = NULL;
         root->rChild = NULL;
     }else if(value > root->data){
         Insert(root->rChild, value);
         root->lChild = root->lChild;
     }else if(value < root->data){
         Insert(root->lChild, value);
         root->rChild = root->rChild;
     }else{
         ;
     }
 }

    void CreateBinaryTree(BianrySearchThree* &tree){
        int data;
        cout<<"input one node data:"<<endl;
        cin>>data;/*等待終端輸入root節點數字,輸入一個數字按回車*/
        if(data == -1){ /*如果用戶輸入-1表示當前節點沒有對應的做孩子或者沒有右孩子*/
            cout<<"there is no child"<<endl;
            tree = NULL;
        }else{/*有數字說明這個節點可以繼續輸入左節點或者右節點*/
            tree = new BianrySearchThree;/*爲這個節點分配空間*/
            tree->data = data;
            /*然後等待輸入左邊節點和右邊節點,如果對應沒有則輸入-1表示*/
            cout<<"input data:"<<tree->data<<" left child;";
            CreateBinaryTree(tree->lChild);
            cout<<"input data:"<<tree->data<<" right child;";
            CreateBinaryTree(tree->rChild);
        }
    }
 
void ShowMiddleTree(BianrySearchThree* root){
     if(NULL == root){
         return;
     }
     ShowMiddleTree(root->lChild);
     cout<<root->data<<" ";
     ShowMiddleTree(root->rChild);
 }
 
void ShowPreTree(BianrySearchThree* root){
    if(NULL == root){
        return;
    }
    cout<<root->data<<" ";
    ShowPreTree(root->lChild);
    ShowPreTree(root->rChild);
}
 
void ShowPostTree(BianrySearchThree* root){
    if(NULL == root){
        return;
    }
    ShowPostTree(root->lChild);
    ShowPostTree(root->rChild);
    cout<<root->data<<" ";
}
 
void BreathSearch(BianrySearchThree* root){
    if(NULL == root){
        return;
    }
    std::queue<BianrySearchThree*> q;
    q.push(root);
    while(!q.empty()){
        BianrySearchThree* node = q.front();
        q.pop();
        cout<<node->data<<" ";
        if(node->lChild){
            q.push(node->lChild);
        }
        if(node->rChild){
            q.push(node->rChild);
        }
    }
}
 
void ShowList(BianrySearchThree* root){
    if(NULL==root)
        return ;
    while(root){
        cout<<root->data<<" ";
        root = root->rChild;
    }
    cout<<endl;
}
 
/*返回鏈表的頭節點
 主要思路:通過遞歸的方式,以及中序遍歷的原理,將樹分爲左邊子樹,root,右子樹
然後:
 1、通過遞歸遍歷到左邊子樹的葉子結點,也就是最左最下以及最小的那個節點。
 2、定義一個臨時的鏈表指針,將這個指針的next指向當前葉子結點,葉子結點的pre指向這個臨時的tail,
 3、然後將這個臨時頭指針向後移動到當前葉子結點。
 4、此時繼續遍歷這個葉子結點的右結點,但是右結點爲空,所以本節點遞歸回退到上一級結點,
 5、此時上一級結點,此時遞歸代碼將會執行到左結點遞歸完成的下一條語句,此時的又把cur結點的pre執行tail結點(此時指向的是開始那個左葉子結點)
 6、然後再把tail->next指向cur這個節點,然後再遞歸k掃描右邊節點(其實就是直接掃描到當前結點最右邊的葉子結點)
 7、此時右進入這個函數,此時這個節點沒有左孩子,就直接執行這個葉子結點指向開始的tail,tail指向這個節點,這樣這個遞歸完成後,函數又回到了
 8、此時就回到再上一級的節點了。z
 9、這樣一級一級的往上走。。。
 注意這裏遞歸的返回其實就是回退到上一級,因爲遞歸其實就是棧的原理,下面的處理完了當回退回去的時候就是彈出處理了的 處理棧剩下了的
 */
void TransferBstToList(BianrySearchThree *head, BianrySearchThree **list_tail){
    if(head == NULL){
        return;
    }
    TransferBstToList(head->lChild, list_tail);
    
    head->lChild = *list_tail;/*當前節點指向tail節點*/
    if(*list_tail){
        (*list_tail)->rChild = head;/*tail節點指向當前節點*/
    }
    
    (*list_tail) = head;/*移動tail指針指向當前節點*/
    
    TransferBstToList(head->rChild, list_tail);
}
 
BianrySearchThree * TransferBstToSortList(BianrySearchThree *head){
 
    if(NULL == head){
        return head;
    }
    
    BianrySearchThree *listTail = NULL;
    
    TransferBstToList(head, &listTail);/*但是這裏得到指針是指向的鏈表的tail位置,所以需要移動到前面去*/
    
    /*往前遍歷*/
    while(listTail && listTail->lChild){
        listTail = listTail->lChild;
    }
    
    return listTail;
}
 

void TransferNode(BianrySearchThree *tree, BianrySearchThree** lastNode){
    if(tree == NULL){
        return;
    }
    
    TransferNode(tree->lChild, lastNode);
    tree->lChild = *(lastNode);
    if(*lastNode){
        (*lastNode)->rChild = tree;
    }
    (*lastNode) = tree;
    TransferNode(tree->rChild, lastNode);
}



BianrySearchThree * TransferBstToDoubleList(BianrySearchThree *tree){
    if(tree == NULL){
        return NULL;
    }
    
    BianrySearchThree *lastNode = NULL;
    
    TransferNode(tree, &lastNode);
    /*這裏不能把lastNode指向了沒有的位置了,因此需要增加一個限制lastNode->lChild不爲空,這裏就限制了這個lastNode做多能走到鏈表頭,而不是指向鏈表頭的lChild(一個空位置)。*/
    while(lastNode && lastNode->lChild){
        lastNode = lastNode->lChild;
    }
    
    return lastNode;
}

int GetSum(BianrySearchThree *tree){
    if(tree == NULL){
        return 0;
    }
    
    if(tree->lChild == NULL && tree->rChild == NULL){
        return tree->data;
    }
    
    int lsum,rSum;
    lsum = GetSum(tree->lChild);
    rSum = GetSum(tree->rChild);
    
    return rSum + lsum + tree->data;
}

void GetSumValuePath(BianrySearchThree *tree, int k, vector<int> &path, vector<vector<int>> &result){
    if(tree == NULL){
        return;
    }
    
    path.push_back(tree->data);
    if(tree->lChild == NULL && tree->rChild == NULL){
        if(tree->data == k){
            result.push_back(path);
        }
        return;
    }
    
    
    GetSumValuePath(tree->lChild, k - tree->data, path, result);
    GetSumValuePath(tree->rChild, k - tree->data, path, result);
    path.pop_back();
    
    
}

void MyPathSum(BianrySearchThree *root, int sum, vector<int> &path, vector<vector<int> > &result)
{
    if(root == NULL) return;
    
    path.push_back(root->data);
    if(root->lChild == NULL && root->rChild == NULL){
        if(sum == root->data){
            result.push_back(path);
        }
    }
    
    if(root->lChild){
        MyPathSum(root->lChild, sum - root->data, path, result);
    }
    
    if(root->rChild){
        MyPathSum(root->rChild, sum - root->data, path, result);
    }
    path.pop_back();
}

int Depth(BianrySearchThree *tree){
    if (NULL == tree){
        return 0;
    }
    
    if(tree->lChild == NULL && tree->rChild == NULL){
        return 1;
    }
    
    int l = Depth(tree->lChild);
    int r = Depth(tree->rChild);
    
    return std::max(l,r) +1;
}

bool IsPostSort(int a[], int start, int end){
    
    for(start; start < end -1; start++){
        if(a[start] > a[end-1]){
            break;
        }
    }
    int lChild = true;
    int lend = start;
    for(start; start < end -1; start++){
        if(a[start] < a[end -1]){
            break;
        }
    }
    int rChild = false;
    if(start == end -1){
        rChild = true;
    }
    int rend = start;
    
    if(lChild & rChild){
        return true;
    }else{
        return false;
    }
    
    bool l = IsPostSort(a, 0, lend);
    bool r = IsPostSort(a, lend, rend);
    
    return l & r;
    
    
    
    
}


void BreathSearchB(BianrySearchThree *tree){
    if(tree == NULL){
        return ;
    }
    
    std::queue<BianrySearchThree *> q;
    q.push(tree);
    //cout<<"BreathSearchB:"<<tree->data<<" ";
    while(!q.empty()){
        //cout<<q.front()->data<<" ";
        //q.pop();
        //cout<<"loop start"<<endl;
        BianrySearchThree* node = q.front();
        q.pop();
        cout<<node->data<<" ";
        if(node->lChild){
            q.push(node->lChild);
            //cout<<"input:"<<node->lChild->data<<" ";
        }
        if(node->rChild){
            q.push(node->rChild);
            //cout<<"input:"<<node->rChild->data<<" ";
        }
        //cout<<"loop end"<<endl;
    }
}

void BreathSearchZZ(BianrySearchThree *tree){
    if(tree == NULL){
        return ;
    }
    
    std::queue<BianrySearchThree *> q;
    q.push(tree);
    int i = 0;
    while(!q.empty()){
        BianrySearchThree* node = q.front();
        q.pop();
        cout<<node->data<<" ";
        if((i)%2 == 0){
            if(node->lChild){
                q.push(node->lChild);
            }
            if(node->rChild){
                q.push(node->rChild);
            }
        }else{
            if(node->rChild){
                q.push(node->rChild);
            }
            if(node->lChild){
                q.push(node->lChild);
            }
        }
        i++;
    }
}


void FindMinKData(vector<int> &a, vector<int> &result, int k){
    /*先排序,在遍歷*/
    for(int i = 0; i < a.size() - 1 ; i++){
        for(int j = 0;j<a.size() - 1;j++){
            if(a[j]>a[j+1])
                swap(a[j], a[j+1]);
        }
    }
    
    for(int i = 0; i < a.size() ; i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;
    
    for(int i = 0; i < k; i++){
        result.push_back(a[i]);
    }
}

struct ListNode{
    int data;
    ListNode *next;
};

bool IsCross(ListNode *head1, ListNode *head2){
    if(head1 == NULL || head2 == NULL){
        return false;
    }
    
    ListNode *list1tail = head1;
    while(list1tail){
        list1tail = list1tail->next;
    }
    ListNode *list2tail = head1;
    while(list2tail){
        list2tail = list2tail->next;
    }
    
    if(list1tail == list2tail){
        return true;
    }
    
    return false;
}

int MaxPath(BianrySearchThree *tree, int &maxPath){
    if(NULL == tree){
        return 0;
    }
    
    if(NULL == tree->lChild && NULL == tree->rChild){
        return 1;
    }
    
    int l = MaxPath(tree->lChild, maxPath) + 1;
    int r = MaxPath(tree->rChild, maxPath) + 1;
    
    int sum = l + r;
    maxPath = max(maxPath, sum);
    
    return (l > r)?l:r;
    
    
}

bool verifySquenceOfBST(int squence[], int length)
{
    if(squence == NULL || length <= 0)
        return false;
    // root of a BST is at the end of post order traversal squence
    int root = squence[length - 1]; // the nodes in left sub-tree are less than the root
    int i = 0;
    for(; i < length - 1; ++ i)
    {
        if(squence[i] > root)
            break;
    } // the nodes in the right sub-tree are greater than the root
    int j = i;
    for(; j < length - 1; ++ j)
    {
        if(squence[j] < root)
            return false;
    } // verify whether the left sub-tree is a BST
    bool left = true;
    if(i > 0)
        left = verifySquenceOfBST(squence, i); // verify whether the right sub-tree is a BST
    bool right = true;
    if(i < length - 1)
        right = verifySquenceOfBST(squence + i, length - i - 1);
    return (left && right);
}

void FindPath(BianrySearchThree* tree, vector<vector<int>> &result, vector<int> &path, int &sum, int &expect){
    if(tree == NULL){
        return;
    }
    
    sum += tree->data;
    path.push_back(tree->data);
    if(tree->lChild == NULL && tree->rChild == NULL){
        if(sum == expect){
            for(auto &t:path){
                cout<<t<<" ";
            }
            result.push_back(path);
            sum = 0;

            cout<<endl;
            path.clear();
        }
        return;
    }
    
    if(tree->lChild){
        FindPath(tree->lChild, result, path, sum, expect);
    }
    
    if(tree->rChild){
        FindPath(tree->rChild, result, path, sum, expect);
    }
}

void PrintPath(BianrySearchThree* pRoot,int sum, const int key)
{
    static deque<int>  stack;
 
    if (pRoot == NULL)
    {
        return;
    }
    if (sum+pRoot->data == key) //如果當前值加上路徑和爲目標值,則輸出
    {
        for (int i = 0; i < stack.size(); i++)
        {
            cout<<stack[i]<<"->";
        }
        cout<<pRoot->data<<endl;
 
        return;
    }
    else if (sum + pRoot->data > key)//如果大於目標值,則返回
    {
        return;
    }
    else//如果小於,則入棧
    {
        stack.push_back(pRoot->data);
        sum += pRoot->data;
 
        PrintPath(pRoot->lChild,sum,key);
        PrintPath(pRoot->rChild,sum,key);
 
        sum -= pRoot->data;
        stack.pop_back();
    }
}

    void replaceSpace(char *str, int length) {
        if (str == NULL || length < 0)
            return;
        else
        {
            int numoforiginal = 0;            //用來統計字符串長度
            int numofspace = 0;                //用來統計空格數
            int i = 0;
            while (str[i] != '\0')
            {
                numoforiginal++;               //統計字符串長度
                if (str[i++] == ' ')
                    numofspace++;              //空格數
            }
            int newoflength = numoforiginal + numofspace * 2;
            //if (newoflength > length)
              //  return;
 
            //從後往前替換空格
            int indexoforiginal =numoforiginal;
            int indexofnew = newoflength;
            while (indexoforiginal >= 0)
            {
                if (str[indexoforiginal] == ' ')
                {
                    str[indexofnew--] = '0';
                    str[indexofnew--] = '2';
                    str[indexofnew--] = '%';
                }
                else
                    str[indexofnew--] = str[indexoforiginal];
                indexoforiginal--;
            }
        }
    }


int main(){
#if 1
    int treeData[9]={6,2,4,10,8,11};
    BianrySearchThree *tree = NULL;
    for(int i = 0; i < 6 ;i++ ){
        Insert(tree,treeData[i]);
        cout<<treeData[i]<<" ";
    }
    cout<<endl;
    //CreateBinaryTree(tree);
    
    ShowPreTree(tree);
    cout<<endl;
    ShowMiddleTree(tree);
    cout<<endl;

    BreathSearchB(tree);
    cout<<"Tree depth="<<Depth(tree)<<endl;
    BreathSearchZZ(tree);

    //BianrySearchThree *list=TransferBstToDoubleList(tree);
    //ShowList(list);
    //cout<<"BST sum = "<<GetSum(tree)<<endl;
    

#endif
    
    /*int treeData[9]={6,2,8,4,10,16,7,13,9};
    BianrySearchThree *tree = NULL;
    for(int i = 0; i < 9 ;i++ ){
        Insert(tree,treeData[i]);
    }
    cout<<endl;
    ShowPreTree(tree);
    vector<vector<int>> result;
    vector<int> path;
    int sum = 0;
    int expect = 22;
    //void FindPath(BianrySearchThree* tree, vector<vector<int>> &result, vector<int> &path, int &sum, int &expect){
    PrintPath(tree, 0,12);
    char zhangyi[]="zhangyi love yangtao";
    replaceSpace(zhangyi, strlen(zhangyi));
    cout<<zhangyi<<endl;*/
    /*i=0 addree:0x7ffeefbff528*/
    
    
    return(0);
}

#else

#include<iostream>
#include <queue>
#include <stack>
#include <string.h>
#include <stdio.h>
using namespace std;

/*冒泡算法*/
void Bubble(vector<int> &a){
    for(int i = 0; i < a.size() - 1; i++){
        for(int j = 0; j < a.size() - 1- i;j++){
            if( a[j] > a[j+1]){
                swap(a[j],a[j+1]);
            }
        }
    }
}

/*選擇排序,就是從第一個數開始,把剩下的數據找到最小的值,然後和第一個數據進行交換
 也就是從後面選一個最大或者最小的值放在最前面。*/
void Select(vector<int> &a){
    for(int i = 0 ; i < a.size(); i++){
        int min = a[i];
        int mindex = i;
        for(int j = i;j< a.size(); j++){
            if(a[j] < min){
                min = a[j];
                mindex = j;
            }
        }
        swap(a[i],a[mindex]);/*交換兩個位置*/
    }
}
/*插入排序的思路是:假設第一額數據已經是一個排好序的數列,然後從剩下的數據中第一個數據和前面的比較,比較
 到比他小的就插入到這個數據之前*/
void InsertSort(vector<int> &a){
    for(int i = 1; i < a.size(); i++){
        /*從下一個數據開始比較*/
        int cmp = a[i];
        for(int j = i; j > 0; j--){
            if(cmp < a[j]){
                a[j+1] = a[j];
            }else{
                a[j+1] = cmp;
                break;
            }
        }
    }
}

void function(vector<int> &data){
    int i, j, tmp;
    for(i = 1; i < data.size(); i++){
        tmp = data[i];
        for( j=i; j > 0 && tmp < data[j-1]; j-- )
            data[j] = data[j-1];
        data[j] = tmp;
    }
}

 void InsertionSort(vector<int> &num,int n)
  {
      int i = 0;
      int j = 0;
      int tmp = 0;
      for(i = 1;i<n;i++)
      {
      tmp = num[i];//從待插入組取出第一個元素。
      j = i-1; //i-1即爲有序組最後一個元素(與待插入元素相鄰)的下標
      while(j>=0&&tmp<num[j])  //注意判斷條件爲兩個,j>=0對其進行邊界限制。第二個爲插入判斷條件
      {
        num[j+1] = num[j];//若不是合適位置,有序組元素向後移動
        j--;
      }
      num[j+1] = tmp;//找到合適位置,將元素插入。
    }
  }

int main(){
    vector<int> a;
    a.push_back(5);
    a.push_back(2);
    a.push_back(4);
    a.push_back(1);
    a.push_back(3);
    for(auto &i:a){
        cout<<i<<" ";
    }
    cout<<endl;
    //Bubble(a);
    //function(a);
    //InsertionSort(a,a.size());
    for(auto &i:a){
        cout<<i<<" ";
    }
    cout<<endl;
    
}

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if (strs.empty())
            return "";for (int idx = 0; idx < strs[0].size(); ++idx) { // 縱向掃描
            for (int i = 1; i < strs.size(); ++i) {
                if (strs[i][idx] != strs[0][idx])
                    return strs[0].substr(0,idx);
            }
        }
        return strs[0];
    }
};

#endif


 
 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章