• tree


    #include <iostream>
    #include <string>
    #include <vector>
    
    using std::cout;
    using std::endl;
    using std::vector;
    using std::string;
    
    namespace chen {
    
    template <typename T>
    class Tree {
    public:
    	Tree(const T& val): val_(val) {}
    	T val() const
    	{return val_;}
    	Tree*& left()
    	{return left_;}
    	Tree*& right()
    	{return right_;}
    
    private:
    	T val_;
    	Tree* left_;
    	Tree* right_;
    }; //Tree
    
    template <typename T>
    Tree<T>* addVal(Tree<T>* root, const T& val)
    {
    	if (!root) {
    		root = new Tree<T>(val);
    		return root;
    	}
    	if (root->val() > val)
    		root->left() = addVal(root->left(), val);
    	else
    		root->right() = addVal(root->right(), val);
    
    	return root;
    }
    
    template <typename T>
    void printTree(Tree<T>* root)
    {
    	if (root) {
    		printTree(root->left());
    		cout << root->val() << endl;
    		printTree(root->right());
    	}
    }
    
    template <typename T>
    void freeTree(Tree<T>** root)
    {
    	if (*root) {
    		freeTree(&(*root)->right());
    		freeTree(&(*root)->right());
    		delete *root;
    		*root = nullptr;
    	}
    }
    
    void TreeTest()
    {
    	vector<int> nums = {100, 78, 123, 45, 98, 113, 189, 234, 1, 19, 54, 100, 123, 654, 98};
    
    	chen::Tree<int>* root = 0;
    	for (auto i : nums) {
    		root = addVal(root, i);
    	}
    	printTree(root);
    	freeTree(&root);
    	printTree(root);
    }
    
    } //namespace chen
    
    
    放弃很容易,但是坚持真的很酷,静享此刻,强风吹拂
  • 相关阅读:
    thinkphp5分页
    thinkphp 获取器、修改器
    Thinkphp中对数据库的基础操作
    MYSQL 数据库内容的分页展示
    单例模式连接数据库
    简单的通过ajax ‘POST’ 方法实现与后台数据交互
    PHP中 .= 的意思
    mysqli 简单的php注册登录功能
    4.4
    梦断代码阅读笔记1
  • 原文地址:https://www.cnblogs.com/joker8/p/15516532.html
Copyright © 2020-2023  润新知