- 27 二叉树的镜像
- 来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof - 请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
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
解题思路:【c++】(1)栈:首先将根节点压入栈,用栈将当前节点的左右节点依次压入栈,直到遍历完整个二叉树的节点,栈为空时返回root。(2)递归:若当前节点为NULL,返回NULL,否则交换其左右节点,需要将原左节点暂时存起来,左节点赋值为原右节点递归返回值,右节点赋值为原左节点递归返回值,返回为当前根节点root。
//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:
TreeNode* mirrorTree(TreeNode* root) {
//solution 1:
// stack<TreeNode*> stackNodes;
// TreeNode *cur_node;
// if(root== NULL) return NULL;
// stackNodes.push(root);
// while(!stackNodes.empty()){
// cur_node= stackNodes.top();
// stackNodes.pop();
// if(cur_node->left!=NULL) stackNodes.push(cur_node->left);
// if(cur_node->right!=NULL) stackNodes.push(cur_node->right);
// TreeNode *node = cur_node->left;
// cur_node->left = cur_node->right;
// cur_node->right = node;
// }
// return root;
//solution 2:
return mirrorTreeBranch(root);
}
TreeNode* mirrorTreeBranch(TreeNode* root){
TreeNode *left_node;
if (root == NULL) return NULL;
left_node = root->left;
root->left = mirrorTreeBranch(root->right);
root->right = mirrorTreeBranch(left_node);
return root;
}
};
# python3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
return self.mirrorTreeBranch(root)
def mirrorTreeBranch(self, root):
if(root):
left_node = root.left
root.left = self.mirrorTreeBranch(root.right)
root.right = self.mirrorTreeBranch(left_node)
return root