层次建树(优先插入左端),求二叉树的深度
#include<iostream> #include<string> #include<unordered_map> #include<queue> using namespace std; struct TreeNode{ char val; int level; int height; struct TreeNode* left; struct TreeNode* right; TreeNode(char x,int lev) :val(x), level(lev), height(1),left(nullptr),right(nullptr){} }; typedef pair<char, int> Pair; struct cmpbyvalue{ bool operator ()(const Pair& v1, const Pair &v2){ return v1.second < v2.second; } }; void create(TreeNode*&root, vector<Pair>& test){//层次建树,利用队列和节点层数来建立 queue<TreeNode*> que_temp; TreeNode* cur=nullptr; for (size_t i = 0; i < test.size();i++){ TreeNode* t = new TreeNode(test[i].first,test[i].second); que_temp.push(t); if (cur == nullptr) //只有第一次调用会执行 cur = que_temp.front(); if (cur->left != nullptr&&cur->right != nullptr){//注意队列中已经排好序了,如果当前节点的左右孩子都不为空了(不能插入),需要从队列获取一个新的结点 que_temp.pop(); cur = que_temp.front(); } if (i == 0){ root = t; } else if ((t->level-cur->level==1)&&cur->left==nullptr){//插入到左子树 cur->left = t; } else if ((t->level - cur->level == 1)//插入到右子树 && cur->right == nullptr){ cur->right = t; } else{ que_temp.pop(); cur = que_temp.front(); if (cur->left != nullptr) cur->left = t; else cur->right = t; } } } int count(TreeNode*& root){//统计所有节点的高度并记录到节点的height中 if (root->left == nullptr&&root->right == nullptr){ root->height = 1; return 1; } if (root->left != nullptr&&root->right!=nullptr){ root->height = max(count(root->left), count(root->right)) + 1; } else if (root->left != nullptr){ root->height = count(root->left) + 1; } else{ root->height = count(root->right) + 1; } return root->height; } TreeNode* print(TreeNode* root,char ch,TreeNode* &point){ if (root == nullptr) return nullptr; if (root->val == ch){ cout << root->height; point = root; return point; } return print(root->left, ch,point); return print(root->right, ch,point); } void Preorder(TreeNode*& root){//先序遍历 if (root == nullptr) return; static int count = 1; if (root != nullptr){ cout << "节点" << count++ << ":" << root->val <<" 层次"<<root->level<<"高度:"<<root->height<< endl; } Preorder(root->left); Preorder(root->right); } int main(){ string str1,str2; while (getline(cin, str1) && getline(cin, str2) && !(str1.size() == 0 && str2.size() == 0)){ size_t start = 0; unordered_map <char, int> que; while (start < str1.size()){ char data = str1[start]; start++; int leve = 0; while (str1[start] <= '9'&&str1[start] >= '0'){ leve = leve * 10 + str1[start] - '0'; start++; } que[data] = leve; } vector<Pair> test(que.begin(), que.end()); sort(test.begin(), test.end(), cmpbyvalue()); TreeNode* root = nullptr; create(root, test); count(root); TreeNode* point = nullptr; int tem = 0; for (size_t s1 = 0; s1 < str2.size(); s1++){ point=print(root, str2[s1],point); if (point ==nullptr) cout << tem; if (s1!=str2.size()-1) cout << " "; } cout << endl; } return 0; }
好像忘记了去释放new出来的内存
手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!