首页 > 代码库 > 逆转二叉树

逆转二叉树

技术分享

逆转二叉树 代码练手

#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

逆转二叉树