• [剑指Offer] 18.二叉树的镜像


    题目描述

    操作给定的二叉树,将其变换为源二叉树的镜像。 
    输入描述:
        	    8
        	   /  
        	  6   10
        	 /   / 
        	5  7 9 11
        	镜像二叉树
        	    8
        	   /  
        	  10   6
        	 /   / 
        	11 9 7  5

    【思路1】递归,左右孩子交换再分别递归左右子树

     1 /*
     2 struct TreeNode {
     3     int val;
     4     struct TreeNode *left;
     5     struct TreeNode *right;
     6     TreeNode(int x) :
     7             val(x), left(NULL), right(NULL) {
     8     }
     9 };*/
    10 class Solution {
    11 public:
    12     void Mirror(TreeNode *pRoot) {
    13         if(pRoot == NULL) 
    14             return ;
    15         TreeNode *temp = pRoot->left;
    16         pRoot->left = pRoot->right;
    17         pRoot->right = temp;
    18         Mirror(pRoot->left);
    19         Mirror(pRoot->right);
    20     }
    21 };

    【思路2】非递归,栈实现

     1 /*
     2 struct TreeNode {
     3     int val;
     4     struct TreeNode *left;
     5     struct TreeNode *right;
     6     TreeNode(int x) :
     7             val(x), left(NULL), right(NULL) {
     8     }
     9 };*/
    10 class Solution {
    11 public:
    12     void Mirror(TreeNode *pRoot) {
    13         if(pRoot == NULL) 
    14             return ;
    15         stack<TreeNode*> StackNode;
    16         StackNode.push(pRoot);
    17         while(!StackNode.empty()){
    18             TreeNode* tree = StackNode.top();
    19             StackNode.pop();
    20             if(tree->left || tree->right){
    21                 TreeNode* temp = tree->left;
    22                 tree->left = tree->right;
    23                 tree->right = temp;
    24             }
    25             if(tree->left)
    26                 StackNode.push(tree->left);
    27             if(tree->right)
    28                 StackNode.push(tree->right);
    29         }
    30     }
    31 };
  • 相关阅读:
    JSP脚本指令
    JSP编译指令——page、include
    c++基础(三):多态
    c++基础(一):数据类型和结构
    c++基础(二):成员he派生类
    python小算法(二)
    python的内存管理
    初识java之Mina(一)
    python的小爬虫的基本写法
    python小算法(一)
  • 原文地址:https://www.cnblogs.com/lca1826/p/6475940.html
Copyright © 2020-2023  润新知