226. Invert Binary Tree
来源:互联网 发布:面料常见花纹知乎 编辑:程序博客网 时间:2024/05/21 20:23
题目大意:
翻转二叉树
思路:递归一下,递归比迭代好写
Python代码:
# Definition for a binary tree node.class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = Noneclass Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root is None: return None temp = root.left root.left = self.invertTree(root.right) root.right = self.invertTree(temp) return root# bfs打印树 def printTree(root): arr = [] arr.append(root) while len(arr) > 0: size = len(arr) for i in range(0, size): node = arr[0] print(node.val, ' ',end = '') if node.left is not None: arr.append(node.left) if node.right is not None: arr.append(node.right) arr.remove(node) print()n4 = TreeNode(4)n2 = TreeNode(2)n7 = TreeNode(7)n1 = TreeNode(1)n3 = TreeNode(3)n6 = TreeNode(6)n9 = TreeNode(9)n4.left = n2n4.right = n7# n2.left = n1# n2.right = n3# n7.left = n6# n7.right = n9printTree(n4)root = Solution().invertTree(n4)printTree(root)
0 0
- 226.Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 3.1面向对象的概念
- 坚持#162天~做事有做事的方法
- 题目1058:反序输出
- 190行LUA撸撸撸了一天。
- 四则运算计算器(面向对象编程思维)
- 226. Invert Binary Tree
- 暑期实习面试总结
- 查看mysql安装路径
- HDU 1242 Rescue
- C#上机实验之题目一
- 第一天
- 六种姿势拿下连续子序列最大和问题,附伪代码(以HDU 1003 1231为例)
- POJ 2533 Longest Ordered Subsequence
- poj1260