• 操作给定的二叉树,将其变换为源二叉树的镜像。


    // ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include "stdafx.h"
    #include<iostream>
    #include<vector>
    #include<algorithm>
    #include<numeric>
    #include<list>
    #include<iterator>
    #include<queue>
    #include<stack>
    using namespace std;
    
    
    
    
    struct TreeNode {
    	int val;
    	struct TreeNode *left;
    	struct TreeNode *right;
    	TreeNode(int x) :
    	val(x), left(NULL), right(NULL) {
    	}
    };
    
    
    class Solution {
    public:
    	void Mirror(TreeNode* &pRoot) {
    		
    		 if (pRoot != NULL && (pRoot->left != NULL || pRoot->right != NULL))
    		{
    			TreeNode *temp = pRoot->left;
    			pRoot->left = pRoot->right;
    			pRoot->right = temp;
    
    			Mirror(pRoot->left);
    			Mirror(pRoot->right);
    		}
    	}
    
    	//先序遍历构建二叉树
    	void preCreate(TreeNode* &T)
    	{
    		int num;
    		cin >> num;
    		if (num == 0) T = NULL;
    		else
    		{
    			T = new TreeNode(num);
    			preCreate(T->left);
    			preCreate(T->right);
    		}
    	}
    
    	//递归的方法先序遍历二叉树
    	void preOrder(TreeNode* &T)
    	{
    		if (T == NULL) return;
    		else
    		{
    			cout << T->val << "  ";
    			preOrder(T->left);
    			preOrder(T->right);
    			
    		}
    	}
    
    
    };
    int main()
    {
    	
    	Solution so;
    	
    	TreeNode*  bi;
    
    
    	so.preCreate(bi);
    	cout << "创建二叉树成功!" << endl;
    
    
    
    	cout << "原二叉树先序遍历:" << endl;
    	so.preOrder(bi);
    	cout << endl;
    
    
    	
    	cout << "镜像二叉树先序遍历:" << endl;
    	so.Mirror(bi);
    	so.preOrder(bi);
    	cout << endl;
    
    
    	cout << endl;
    	return 0;
    }
  • 相关阅读:
    java中this()、super()的用法和区别
    线段树基础操作
    普通平衡树的基础操作
    简单dp问题汇总
    欧拉线性筛法打表素数
    单调队列与dp的关系
    最全的常用正则表达式大全——包括校验数字、字符、一些特殊的需求等等
    常用chrome扩展程序
    各种数据类型的字节数
    排查mysql的奇怪问题
  • 原文地址:https://www.cnblogs.com/wdan2016/p/5985344.html
Copyright © 2020-2023  润新知