关于面试:每日一题二叉树的镜像

3次阅读

共计 691 个字符,预计需要花费 2 分钟才能阅读完成。

题目


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

数据范畴:二叉树的节点数 0≤n≤1000,二叉树每个节点的值 0≤val≤1000

要求:空间复杂度 O(n)。本题也有原地操作,即空间复杂度 O(1) 的解法,工夫复杂度 O(n)

比方:
源二叉树

镜像二叉树

参数阐明:二叉树类,二叉树序列化是通过按层遍历,# 代表这这个节点为空节点,举个例子:

  1
 / \
2   3
   /
  4

以上二叉树会被序列化为 {1,2,3,#,#,4}

示例 1

 输出:{8,6,10,5,7,9,11}
返回值:{8,10,6,11,9,7,5}

示例 2

 输出:{}
返回值:{}

思路


  • 递归的替换左右子树
  • 应用栈辅助,dfs 遍历二叉树,替换左右子节点。(解答略)

解答代码


/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 *    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * @param pRoot TreeNode 类 
     * @return TreeNode 类
     */
    TreeNode* Mirror(TreeNode* pRoot) {
        // write code here
        if (pRoot == nullptr) {return nullptr;}
        auto newRoot = new TreeNode(pRoot->val);
        newRoot->left = Mirror(pRoot->right);
        newRoot->right = Mirror(pRoot->left);
        return newRoot;
    }
};
正文完
 0