二叉树-建立/遍历/深度
假如要建立这样的一颗二叉树:
建立二叉树树一共有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;
}