• 逆转二叉树


    逆转二叉树 代码练手

    #include <iostream>
    #include <memory>
    using namespace std;
    
    struct TreeNode{
    	int val;
    	shared_ptr<TreeNode> left;
    	shared_ptr<TreeNode> right;
    };
    
    
    void PrintTree(shared_ptr<TreeNode> root)
    {
    	if (!root)
    		return;
    	cout << root->val << "  ";
    	PrintTree(root->left);
    	PrintTree(root->right);
    	return;
    }
    
    shared_ptr<TreeNode>  CreateNode(int i)
    {
    	shared_ptr<TreeNode> p(new TreeNode());
    	p->val = i;
    	return p;
    }
    
    void InsertNode(shared_ptr<TreeNode>& root,int i)
    {
    	if (!root)
    	{
    		root = CreateNode(i);
    		return;
    	}
    	if (i > root->val)
    	{
    		InsertNode(root->right, i);
    	}
    	else if (i < root->val)
    	{ 
    		InsertNode(root->left, i);
    	}
    	else if (i == root->val)
    		return;
    	return;
    }
    
    
    shared_ptr<TreeNode> InvertTree(shared_ptr<TreeNode>& root )
    {
    	if (!root)
    		return root;
    	shared_ptr<TreeNode> tmp = root->left;
    	root->left = InvertTree(root->right);
    	root->right = InvertTree(tmp);
    	return root;
    }
    
    
    int main()
    {
    	shared_ptr<TreeNode> root = CreateNode(4);
    	InsertNode(root, 2);
    	InsertNode(root, 7);
    	InsertNode(root, 1);
    	InsertNode(root, 3);
    	InsertNode(root, 6);
    	InsertNode(root, 9);
    
    	PrintTree(root);
    
    	InvertTree(root);
    	cout << endl;
    	PrintTree(root);
    
        return 0;
    }
    

      输出:

    4 2 1 3 7 6 9
    4 7 9 6 2 3 1

  • 相关阅读:
    OCP-1Z0-053-V12.02-15题
    Boost.Asio性能测试
    使用asio搭建服务器
    boost::asio::ip::tcp::socket is connected?(如何知道socket的链接是链接或断开?)
    boost::async_read_some连续接收数据
    基于boost asio实现的支持ssl的通用socket框架
    Boost.Asio的使用技巧
    Matlab基本函数-expm函数
    Matlab基本函数-exp函数
    OCP-1Z0-053-V12.02-337题
  • 原文地址:https://www.cnblogs.com/itdef/p/6082792.html
Copyright © 2020-2023  润新知