Invert Binary Tree
2015-07-31 15:44
246 查看
题目:
Invert a binary tree.
to
解题思路:
此题就是对树的结构一些应用以及对递归的考察。解答此题时,破费一些时间,说明对树与递归还未完全 熟悉。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self, root):
if root==None or (root.left==None and root.right==None):
return root
elif root.left!=None and root.right!=None:
root.left, root.right=self.invertTree(root.right), self.invertTree(root.left)
return root
elif root.left!=None:
root.right = self.invertTree(root.left)
root.left = None
return root
elif root.right!=None:
root.left = self.invertTree(root.right)
root.right = None
return root
Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9
to
4 / \ 7 2 / \ / \ 9 6 3 1
解题思路:
此题就是对树的结构一些应用以及对递归的考察。解答此题时,破费一些时间,说明对树与递归还未完全 熟悉。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self, root):
if root==None or (root.left==None and root.right==None):
return root
elif root.left!=None and root.right!=None:
root.left, root.right=self.invertTree(root.right), self.invertTree(root.left)
return root
elif root.left!=None:
root.right = self.invertTree(root.left)
root.left = None
return root
elif root.right!=None:
root.left = self.invertTree(root.right)
root.right = None
return root
相关文章推荐
- swift学习之函数(一)
- 快速排序
- JAVA基本类型和引用类型
- muduo网络库预备知识点
- 【HDOJ 1010】Tempter of the Bone
- Linux 下.desktop 桌面程序图标文件编写方式
- PHP读取CSV文件把数据插入到数据库,本地没有问题,阿里云测试服务器不行
- 统计图表类库--libchart使用简介
- Firefox和Chrome谷歌浏览器显示正在连接打开网页缓慢的解决方法
- ubuntu-64位 error while loading shared libraries: libuuid.so.1: wrong ELF class: ELFCLASS64
- Contiki学习笔记——RPL协议详解
- POJ 1519:Digital Roots
- 从决策树学习谈到贝叶斯分类算法、EM、HMM
- linux panic 和 bug_on
- 【特征工程】特征工程技术与方法
- 分布式系统与集中式系统初探
- Ubuntu终端文件的压缩和解压缩命令
- servlet什么时候被实例化?【转】
- POJ 1519:Digital Roots
- sprintf