二叉树

来源:互联网 发布:恺英网络薪资待遇 编辑:程序博客网 时间:2024/06/07 07:35

二叉树构建

创建节点

class Node{public:    char data;    Node * left;    Node * right;    Node(char data){        this->data = data;        left = right = NULL;    }};//创建一个节点Node* node = new Node('D');//删除一个节点delete node;node = NULL;

二叉树遍历

先序/中序/后序
以后序为例

void post_order(Node *root){    if (root){        post_order(root->left);        post_order(root->right);        cout<<root->data;    }}

有先序和后序构建二叉树

Node* build_tree(string preOrder,string inOrder){    Node* root = new Node(preOrder[0]);    int position = inOrder.find(preOrder[0]);    if (position>=1){        root->left = build_tree(preOrder.substr(1,position),inOrder.substr(0,position));    }    if (inOrder.length()-1>position){        root->right = build_tree(preOrder.substr(position+1,preOrder.length()-1-position),inOrder.substr(position+1,inOrder.length()-1-position));    }    return root;}

注意字符串的构造:string(str,start,num);
另解:

Node *build_Tree(int *a,int *b,int a_start , int a_end , int b_start, int b_end ){    Node *result = NULL;    //先检测是否合法    int k=b_start;    for(;k<=b_end;k++){        if(b[k]==a[a_start]){            break;        }    }    if (k>b_end){        flag = false;    }else{        result = new Node(a[a_start]);        int len = k-b_start;        if(k>b_start){            result->left = build_Tree(a,b,a_start+1,a_start+len,b_start,k-1);        }        if(k<b_end){            result->right = build_Tree(a,b,a_start+len+1,a_end,k+1,b_end);        }    }    return result;}

二叉树的其他操作

求解二叉树的镜像

void reverse_Tree(Node *root){    if (root==NULL)        return;    if(root->left){        reverse_Tree(root->left);    }    if(root->right){        reverse_Tree(root->right);    }    Node *temp = root->left;    root->left = root->right;    root->right = temp;}

求解树的高度

思路:就是左子树和右子树的高度较大的一个,再加1.

int getdeep(Node *root){    int deep = 0;    if (root){        deep = 1 + max(getdeep(root->left),getdeep(root->right));    }    return deep;}

从上向下遍历二叉树

实际上就是一个广度优先遍历。可以通过队列来实现

queue<Node*> q;        q.push(a[1]);        Node *temp;        while(!q.empty()){            temp = q.front();            q.pop();            result[k++] = temp->value;            if(temp->left)                q.push(temp->left);            if(temp->right)                q.push(temp->right);        }

需要注意的是queue的相关操作:
push() 入队
front() 队首
empty() 是否为空
pop() 从队首出队

深度优先搜索

void search_node(Node *root,int temp_sum ,int sum,int k){    if(root==NULL)        return;    temp_sum = temp_sum+root->value;    if(temp_sum>sum)        return;    trace[top++] = root->id;    if(root->left==NULL&&root->right==NULL&&temp_sum==sum){        printf("A path is found:");        for(int m=0;m<top;m++){            printf(" %d",trace[m]);        }        printf("\n");    }    search_node(root->left,temp_sum,sum,k+1);    top = k;    search_node(root->right,temp_sum,sum,k+1);}

完全二叉树

注意:左右叶子节点=父节点×2,父节点×2+1

完全二叉树,第d层,起始为第2^d个节点,一共有2^d个节点

0 0
原创粉丝点击