前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode-面试题27-二叉树的镜像

LeetCode-面试题27-二叉树的镜像

作者头像
benym
发布2022-07-14 15:13:05
1390
发布2022-07-14 15:13:05
举报
文章被收录于专栏:后端知识体系

# LeetCode-面试题27-二叉树的镜像

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

例如输入:

代码语言:javascript
复制
     4
   /   \
  2     7
 / \   / \
1   3 6   9

镜像输出:

代码语言:javascript
复制
     4
   /   \
  7     2
 / \   / \
9   6 3   1

示例1:

代码语言:javascript
复制
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

限制:

0 <= 节点个数 <= 1000

# 解题思路

方法1、递归:

一个二叉树的镜像就是把原本的子节点交换,一层一层来看,先要交换root节点的左右节点,然后分别交换左右节点的子节点,利用递归解决,终止条件是当遍历到左右子树为空或者头结点为空时跳出。

方法2、栈:

类似于DFS的解法,利用一个辅助栈当root为空||root的左右节点为空时返回null

初始化一个栈,存放头节点root,

然后进行循环:当stack为空的时候跳出,

之后的原理是,弹出一个节点node,找到这个节点的左右邻居节点(邻居不为空时),并压入栈中,交换2个左右节点的值

最后返回根节点root

# Java代码

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null)
            return root;
        if(root.left==null&&root.right==null)
            return root;
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        if(root.left!=null)
            mirrorTree(root.left);
        if(root.right!=null)
            mirrorTree(root.right);
        return root;
    }
}

# Python代码

代码语言:javascript
复制
# 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:
        if not root: return root
        if not root.left and not root.right: return root
        stack = [root]
        while stack:
            node = stack.pop()
            if node.left: stack.append(node.left)
            if node.right: stack.append(node.right)
            node.left,node.right = node.right,node.left
        return root
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-04-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • # LeetCode-面试题27-二叉树的镜像
    • # 解题思路
      • # Java代码
        • # Python代码
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档