1. 程式人生 > 實用技巧 >二叉樹-建立/遍歷/深度

二叉樹-建立/遍歷/深度

假如要建立這樣的一顆二叉樹:

建立二叉樹樹一共有2種比較普遍的辦法:

  • 連結串列法:結點伴有其左右孩子結點的指標,遞迴構建
  • 陣列法;陣列法主要記錄二叉樹結點的值與陣列位置的對映關係來構建。但其對二叉樹的結構要求比較嚴格,如果二叉樹變成一條線一樣的話,那就比較耗費記憶體,會有很多空值。
#include <iostream>
#include <vector>
#include <stack>
#include <map>
#include <string>
#include <math.h>
#include <cstdlib>
#include<cstdio>
#include<cstring>
#include<algorithm>


using namespace std;

struct Node{
    char val;
    Node *left;
    Node *right;
};

class Tree{
private:
    Node *tree;
    void build_tree(vector<char> pre_order, int &idx, Node *&root);
public:
    void build_tree(vector<char> pre_order, int idx);
    void pre_order(Node *root);
    int get_depth(Node *root);
    Node *get_root();
};


void Tree::build_tree(vector<char> pre_order, int &idx, Node *&root){
    if(idx>=pre_order.size())
        return;

    char ele = pre_order[idx];
    idx += 1;

    if(ele=='#')
        root = NULL;
    else{
        root = new Node;
        root->val = ele;
        build_tree(pre_order,idx, root->left);
        build_tree(pre_order,idx, root->right);
    }
}

void Tree::build_tree(vector<char> pre_order, int idx){
    this->build_tree(pre_order, idx, tree);
}

void Tree::pre_order(Node *root){
    if(root){
        cout<<root->val<<" ";
        pre_order(root->left);
        pre_order(root->right);
    }else{
        cout<<"# ";
    }
}

Node *Tree::get_root(){
    return tree;
}

int Tree::get_depth(Node *root){
    //get depth using deep first search
    
    stack<pair<Node*, int>> dfs_stack;
    pair<Node*,int> p1(root,1);
    dfs_stack.push(p1);

    pair<Node *,int> tmp_pair;
    Node *tmp_node;
    int depth = 0;
    int curr_depth = 0;
    while(!dfs_stack.empty()){
        tmp_pair = dfs_stack.top();
        tmp_node = tmp_pair.first;
        curr_depth = tmp_pair.second;
        depth = max(depth, curr_depth);
        dfs_stack.pop();

        if(tmp_node->left){
            pair<Node*,int> p1(tmp_node->left,curr_depth+1);
            dfs_stack.push(p1);
        }
        if(tmp_node->right){
            pair<Node*,int> p1(tmp_node->right,curr_depth+1);
            dfs_stack.push(p1);
        }

    }
    return depth;
}




int main(int argc, char const *argv[]){

    vector<char> arr = {'A','B','C','#','#','D','E','#','G','#','#','F','#','#','#'};

    Tree tree;
    tree.build_tree(arr,0);
    Node *root = tree.get_root();
    tree.pre_order(root);
    cout<<endl;
    cout<<tree.get_depth(root)<<endl;

    return 0;
}