AcWing 38. 二叉树的镜像

习题地址 https://www.acwing.com/solution/acwing/content/2922/

题目描述
输入一个二叉树,将它变换为它的镜像。

样例

输入树:
      8
     / \
    6  10
   / \ / \
  5  7 9 11

 [8,6,10,5,7,9,11,null,null,null,null,null,null,null,null] 
输出树:
      8
     / \
    10  6
   / \ / \
  11 9 7  5

 [8,10,6,11,9,7,5,null,null,null,null,null,null,null,null]

 

算法1
基本上大部分树的问题都是要使用递归遍历解决(剑指OFFER和LEETCODE)

先写递归 在递归的返回路径上由下至上的交换左右子树

C++ 代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void dfs(TreeNode* root){
        if(root == NULL)
            return;
        dfs(root->right);
        dfs(root->left);
        swap(root->right,root->left);
    }

    void mirror(TreeNode* root) {
        dfs(root);     
    }
};

作者:defddr
链接:https://www.acwing.com/solution/acwing/content/2922/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

posted on 2019-07-19 09:18  itdef  阅读(141)  评论(0编辑  收藏  举报

导航