zoukankan      html  css  js  c++  java
  • A1102 Invert a Binary Tree [反转二叉树/镜像]

    在这里插入图片描述
    给一棵二叉树子节点下标,要求反转二叉树,之后按要求输出层序和中序遍历。
    思路:因为是给的子节点下标,用二叉树的静态写法会更加方便,找出根节点后,按照后序遍历反转二叉树(交换左右子树),然后再按照模板层序中序遍历输出

    #include<iostream>
    #include<vector>
    #include<queue>
    #include<stack>
    using namespace std;
    const int maxn = 110;
    struct node
    {
    	int lchild, rchild;
    }Node[maxn];
    bool notroot[maxn] = { false };
    int n, num = 0;
    void print(int id)
    {
    	cout << id;
    	num++;
    	if (num < n)
    		cout << " ";
    	else
    		cout << endl;
    }
    void bfs(int root)
    {
    	queue<int>q;
    	q.push(root);
    	while (!q.empty())
    	{
    		int temp = q.front();
    		q.pop();
    		print(temp);
    		if (Node[temp].lchild != -1)
    			q.push(Node[temp].lchild);
    		if (Node[temp].rchild != -1)
    			q.push(Node[temp].rchild);
    	}
    }
    void inorder(int root)
    {
    	if (root == -1)
    		return;
    	inorder(Node[root].lchild);
    	print(root);
    	inorder(Node[root].rchild);
    }
    void postorder(int root)
    {
    	if (root == -1)
    		return;
    	postorder(Node[root].lchild);
    	postorder(Node[root].rchild);
    	swap(Node[root].lchild, Node[root].rchild);
    }
    int strTonum(char c)
    {
    	if (c == '-')
    		return -1;
    	else
    	{
    		notroot[c - '0'] = true;
    		return c - '0';
    	}
    }
    int findroot()
    {
    	for (int i = 0; i < n; i++)
    	{
    		if (notroot[i] == false)
    			return i;
    	}
    }
    int main()
    {
    	char lchild, rchild;
    	cin >> n;
    	for (int i = 0; i < n; i++)
    	{
    		cin >> lchild >> rchild;
    		Node[i].lchild = strTonum(lchild);
    		Node[i].rchild = strTonum(rchild);
    	}
    	int root = findroot();
    	postorder(root);
    	bfs(root);
    	num = 0;
    	inorder(root);
    }
    
  • 相关阅读:
    [转载]windows进程中的内存结构
    RTTI和4个强制转换运算符
    由于应用程序配置不正确,程序未能启动
    光照
    服务器数据同步
    SAP
    PHP输入流php://input
    五款常用mysql slow log分析工具的比较
    开发搜索引擎–PHP中文分词
    大型网站调试工具之一(php性能优化分析工具XDebug)
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812017.html
Copyright © 2011-2022 走看看