leetcode with python -> tree
100. Same Tree
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3 [1,2,3], [1,2,3] Output: true
Example 2:
Input: 1 1
/ \
2 2 [1,2], [1,null,2] Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2 [1,2,1], [1,1,2] Output: false
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
return p.val==q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) if p and q else p is q # one liner
104. Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if(root is None):
return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
107. Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res, queue = [], [root]
while queue:
res.append([node.val for node in queue if node])
queue = [child for node in queue if node for child in (node.left, node.right)]
return res[-2::-1] # elements in each layer should be contained in a list
# res[-2::-1] will reverse the list res[0:-2]
108. Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None mid = len(nums) // 2
root = TreeNode(nums[mid]) root.left = self.sortedArrayToBST(nums[:mid])
root.right = self.sortedArrayToBST(nums[mid+1:]) return root # !!!!! when a == [] , a is not None !!!!!!!!!!
111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if(root is None): return 0
if(root.left is None and root.right is None): return 1
if(root.left is None or root.right is None): return (max(self.minDepth(root.left),self.minDepth(root.right))+1)
else: return (min(self.minDepth(root.left),self.minDepth(root.right))+1) # a bit more difficult than the maxDepth one
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def depth(root):
if root is None: return 0
dep_l = depth(root.left)
dep_r = depth(root.right)
if dep_l == -1 or dep_r == -1 or abs(dep_l - dep_r)>1:
return -1
return max(dep_l, dep_r)+1 return depth(root) != -1 # use a special number as a sign of unqualified tree
112. Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None: return False
if root.left is None and root.right is None and sum == root.val: return True
return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)
leetcode with python -> tree的更多相关文章
- [LeetCode] 107. Binary Tree Level Order Traversal II 二叉树层序遍历 II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...
- [LeetCode] 144. Binary Tree Preorder Traversal 二叉树的先序遍历
Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...
- [LeetCode] 199. Binary Tree Right Side View 二叉树的右侧视图
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nod ...
- [LeetCode] 298. Binary Tree Longest Consecutive Sequence 二叉树最长连续序列
Given a binary tree, find the length of the longest consecutive sequence path. The path refers to an ...
- [LeetCode] 549. Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之 II
Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree. Especia ...
- leetcode 199 :Binary Tree Right Side View
// 我的代码 package Leetcode; /** * 199. Binary Tree Right Side View * address: https://leetcode.com/pro ...
- Leetcode 101 Symmetric Tree 二叉树
判断一棵树是否自对称 可以回忆我们做过的Leetcode 100 Same Tree 二叉树和Leetcode 226 Invert Binary Tree 二叉树 先可以将左子树进行Invert B ...
- LeetCode:Construct Binary Tree from Inorder and Postorder Traversal,Construct Binary Tree from Preorder and Inorder Traversal
LeetCode:Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder trav ...
- (二叉树 递归) leetcode 145. Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes' values. Example: Input: [1,null,2, ...
随机推荐
- Chrome Java插件过期
企业应用软件中,基本都是基于某个版本的JDK进行开发的,更新跟不上Oracle更新的步伐,Chrome浏览器自动默认关闭了过期插件导致用Chrome无法打开应用软件. 解决办法如下:
- Burpsuite Professional安装及使用教程
转自:https://www.jianshu.com/p/edbd68d7c341 1.先从吾爱破解论坛下载工具:https://down.52pojie.cn/Tools/Network_Analy ...
- nmap -sT
将与目标端口进行三次握手,尝试建立连接,如果连接成功,则端口开放,慢,且会被目录主机记录
- 大会聚焦 | 开源技术盛会LinuxCon首次来到中国,大咖齐聚关注业界动态
2017年6月19-20日,开源技术盛会LinuxCon + ContainerCon + CloudOpen(LC3)首次在中国举行.两天议程满满,包括 17 个主旨演讲.8 个分会场的 88 场技 ...
- 加载动画插件spin.js的使用随笔
背景: 在请求后台的“漫长”等待过程中,为了提升用户体验,需要一个类似 的加载动画效果,让用户明确现在处于请求过程中,而不是机子down掉或者网站死了 静态demo(未与后台交互): HTML代码如 ...
- java面试题(杨晓峰)---第二讲Exception和Error有什么区别?
本人总结: Exception和Error:正常问题和意外问题,以自行车举例:没气和爆胎. ①理解Throwable,Exception,Error的设计和分类. ②掌握哪些应用最广泛的子类, ③如何 ...
- python基础教程总结10——文件
1.打开文件 open(name[mode[,buffing]) 参数: 文件,模式,缓冲 1)name: 是强制选项,模式和缓冲是可选的 #如果文件不在,会报下面错误1 >>&g ...
- codeforce Gym 100500C ICPC Giveaways(水)
读懂题意就是水题,按照出现次数对下标排一下序,暴力.. #include<cstdio> #include<algorithm> #include<cstring> ...
- [论文理解] Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks
Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks 简介 Faster R-CNN是很经典的t ...
- js倒计时小插件(兼容大部分浏览器)
精确到天的倒计时 <script language="JavaScript"> <!-- // (c) Henryk Gajewski var urodz= ne ...