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

  • 相关阅读:
    排序算法
    【转】《分享一下我研究SQLSERVER以来收集的笔记》未整理
    D3.js学习记录
    D3.js学习记录【转】【新】
    JAVA FILE or I/O学习
    JAVA GUI学习
    android一键锁屏
    源文件如何转换到可执行文件
    手动搭建maven项目
    ThinkingInJava----第11章 持有对象
  • 原文地址:https://www.cnblogs.com/itdef/p/6082792.html
Copyright © 2011-2022 走看看