226. Invert Binary Tree
来源:互联网 发布:pythonpath linux 编辑:程序博客网 时间:2024/06/06 00:08
题意:Invert a binary tree.
4 / \ 2 7 / \ / \1 3 6 9
to
4 / \ 7 2 / \ / \9 6 3 1
思路:这题很简单,无非两种思路,栈或者递归,栈是从根到叶操作的,递归是从叶到根操作的。但是这里我一开始把代码错写成了:
def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root: # root.left.val,root.right.val = root.right.val,root.left.val root.left = self.invertTree(root.right) root.right = self.invertTree(root.left) return root
这相当于所有结果都以右侧的结点来替代,结果当然是错的,正确的代码如下:
def invertTree(self, root): if root: root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root
由于python赋值语句的特点,左右子树的函数同时作用,当然还有用栈的代码:
def invertTree(self, root): stack = [root] while stack: node = stack.pop() if node: node.left, node.right = node.right, node.left stack += node.left, node.right return 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
- Backbone.js中的Events模块如何使用?
- 链表-E-实现队列
- 计算机操作系统知识图谱
- 数论(多个数gcd) CodeForces757B Bash's Big Day
- CentOS 7下MySQL 5.7安装、配置与应用
- 226. Invert Binary Tree
- 链表-F-有序链表
- 链表-G- 利用有序链表给数组排序
- Unity3d调用Anroid(Android Studio环境)方法
- Javascript如何实现二分查找?
- Log4net配置与使用简要说明
- 链表-H-双向链表,允许前后遍历
- 高质量的SRS的一些特性
- 链表-I-链表实现迭代器