JZ18 二叉树镜像

JZ18 二叉树镜像

题目

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

思路

  • 先遍历, 节点入栈, 再依次出栈调换左右节点
  • 遍历的过程中调换左右节点

代码

1# -*- coding:utf-8 -*- 2class TreeNode: 3 def __init__(self, x): 4 self.val = x 5 self.left = None 6 self.right = None 7 8# -*- coding:utf-8 -*- 9# class TreeNode: 10# def __init__(self, x): 11# self.val = x 12# self.left = None 13# self.right = None 14class Solution: 15 # 先遍历, 入栈, 再调换左右节点 16 def Mirror(self, root): 17 # 判断传入节点是否为空 18 if root is None: 19 return None 20 line_node = self.printLevelNode(root) 21 # print(line_node) 22 while line_node: 23 tmp = line_node.pop() 24 if tmp.left or tmp.right: 25 tmp.left, tmp.right = tmp.right, tmp.left 26 return tmp 27 # 层次遍历二叉树, 被调用 28 def printLevelNode(self, root): 29 line_node = [] 30 res = [] 31 line_node.append(root) 32 while line_node: 33 tmp = line_node.pop(0) 34 res.append(tmp) 35 if tmp.left: 36 line_node.append(tmp.left) 37 if tmp.right: 38 line_node.append(tmp.right) 39 return res 40 41 # 层次遍历的过程中调换左右节点 42 def Mirror2(self, root): 43 if root is None: 44 return None 45 line_node = [] 46 line_node.append(root) 47 while line_node: 48 tmp = line_node.pop(0) 49 if tmp.left: 50 line_node.append(tmp.left) 51 if tmp.right: 52 line_node.append(tmp.right) 53 # if tmp.left or tmp.right: 54 tmp.left, tmp.right = tmp.right, tmp.left 55 return root 56 57 # 递归遍历的过程中调换左右节点 58 def Mirror3(self, root): 59 if root is None: 60 return None 61 root.left, root.right = root.right, root.left 62 self.Mirror3(root.left) 63 self.Mirror3(root.right) 64 return root 65 66 67if __name__ == '__main__': 68 node1 = TreeNode(8) 69 node2 = TreeNode(6) 70 node3 = TreeNode(10) 71 node4 = TreeNode(5) 72 node5 = TreeNode(7) 73 node6 = TreeNode(9) 74 node7 = TreeNode(11) 75 node1.left = node2 76 node1.right = node3 77 node2.left = node4 78 node2.right = node5 79 node3.left = node6 80 node3.right = node7 81 sl = Solution() 82 ls = sl.Mirror3(node1) 83 print(ls) 84 for i in sl.printLevelNode(ls): 85 print(i.val)
点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

js实现二叉树、二叉查找树

树是一种数据结构,该章节讨论二叉树(二叉树的每个节点的子节点不允许超过两个),二叉树中有又分为完全二叉树和不完全二叉树.....不在本章节赘述相关概念,感兴趣可以去查阅《数据结构》。你将会获得:1.如何使用js实现二叉查找树。2.学会前、中、后序遍历。3.了解相关实现原理阅读时长5min,可选择直接调试代码特点    二叉查找树中序遍历后

用C语言的递归写个二叉搜索树(二叉排序树)

不会递归的程序员不是好程序员,虽然鄙人尚未毕业,是个无知的大学生。但这追去真理的上进心不可小量。二叉树的每一个节点,与其左右子树都可以组成一个二叉树,利用这思路,可以写个递归形式的二叉树。cinclude<stdio.hinclude<stdlib.htypedefstructtreeNodeintdata;structtreeNodeLeft

二叉树创建后,如何使用递归和栈遍历二叉树?

0.前言前文主要介绍了树的相关概念和原理,本文主要内容为二叉树的创建及遍历的代码实现,其中包括递归遍历和栈遍历。1.二叉树的实现思路1.0.顺序存储——数组实现前面介绍了满二叉树和完全二叉树,我们对其进行了编号——从0到n的不中断顺序编号,而恰好,数组也有一个这样的编号——数组下标,只要我们把二者联合起来,数组就能存储二叉树了。那么非满

JAVA递归实现线索化二叉树

JAVA递归实现线索化二叉树基础理论首先,二叉树递归遍历分为先序遍历、中序遍历和后序遍历。先序遍历为:根节点左子树右子树中序遍历为:左子树根节点右子树后序遍历为:左子树右子树根节点(只要记住根节点在哪里就是什么遍历,且都是先左再右)线索化现在有这么一棵二叉树,它的数据结

LeetCode(110):平衡二叉树

Easy!题目描述:给定一个二叉树,判断它是否是高度平衡的二叉树。本题中,一棵高度平衡二叉树定义为:一个二叉树_每个节点_的左右两个子树的高度差的绝对值不超过1。示例1:给定二叉树 3,9,20,null,null,15,73/\920/

JZ18 二叉树镜像 - HelloWorld