cherrychenlee

导航

 

原文地址:https://www.jianshu.com/p/0709c0a61b49

时间限制:1秒 空间限制:32768K

题目描述

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

输入描述

图1 二叉树的镜像定义

/*
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==nullptr)
            return;
        TreeNode* tmp=pRoot->left;
        pRoot->left=pRoot->right;
        pRoot->right=tmp;
        if(pRoot->left)
            Mirror(pRoot->left);
        if(pRoot->right)
            Mirror(pRoot->right);
        return;
    }
};

运行时间:8ms
占用内存:592k

/*
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==nullptr)
            return;
        stack<TreeNode*> st;
        st.push(pRoot);
        while(!st.empty()){
            TreeNode* root=st.top();st.pop();
            if(root->left || root->right){
                TreeNode* tmp=root->left;
                root->left=root->right;
                root->right=tmp;
            }
            if(root->left)
                st.push(root->left);
            if(root->right)
                st.push(root->right);
        }
        return;
    }
};

运行时间:4ms
占用内存:496k

posted on 2019-04-27 23:00  cherrychenlee  阅读(95)  评论(0编辑  收藏  举报