剑指offer:面试题27. 二叉树的镜像

题目:二叉树的镜像

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

例如输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
镜像输出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

限制:

0 <= 节点个数 <= 1000

解题:

方法一:递归

先定义一个递归出口:当递归到null节点时,直接返回null。接着如果当前节点不是null节点,则其左右孩子调换。最后继续递归下去。解题思想是只考虑当前层孩子的调换,不用考虑下面层的事情。

/**
 * 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:
    TreeNode* mirrorTree(TreeNode* root) {
        if(root == nullptr) return nullptr;

        TreeNode* temp = root->left;
        root->left = root->right;
        root->right = temp;
        mirrorTree(root->left);
        mirrorTree(root->right);

        return root;
    }
};

方法二:栈

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        stack<TreeNode*> s;
        s.push(root);
        while (!s.empty()) {
            TreeNode* node = s.top();
            s.pop();
            if (node == NULL) {
                continue;
            }
            swap(node->left, node->right);
            s.push(node->left); 
            s.push(node->right);
        }
        return root;
    }
};
发布了106 篇原创文章 · 获赞 113 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/qq_41598072/article/details/104498919