zoukankan      html  css  js  c++  java
  • 逆转二叉树

    逆转二叉树 代码练手

    #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

  • 相关阅读:
    Android 源代码在线查看
    Android天气预报程序开发
    为自己的网站写个api接口
    Windows Server 2012改造成Windows8的方法(新增解决网络卡)
    完整java开发中JDBC连接数据库代码和步骤
    RF频偏
    通信系统架构,RF架构
    RF 速率与引导码preamble关系
    ubuntu虚拟机共享无线网上网
    win7下AdHoc网络设置共享外网上网
  • 原文地址:https://www.cnblogs.com/itdef/p/6082792.html
Copyright © 2011-2022 走看看