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, ...
随机推荐
- centos 离线安装 mysql 5.7
1 . 安装新版mysql前,需将系统自带的mariadb-lib卸载. rpm -qa|grep mariadb mariadb-libs--.el7.centos.x86_64 rpm -e -- ...
- Android--View事件传递
Android--View事件传递 View事件传递首先要明白以下要素: 事件就是MotionEvent.该对象包含了传递的事件中的所有信息 事件的来源是Window(即PhoneWindow),包含 ...
- python之map,zip,reduce,filter的用法
1.reduce(func,iterable,initial): 参数: - func 可执行函数 - iterable 可迭代对象 - initial 可选,初始参数 功能描述:调用func函数后, ...
- JAVA-Web05
1 HTTP协议特点 1)客户端->服务端(请求request)有三部份 a)请求行 b)请求头 c)请求的内容,如果没有,就是空白字符 2)服务端->客户端(响应respon ...
- MovieReview—Kingsman THE SECRET SERVICE(王牌特工之特工学院)
Brain Storming Mr. Valentine's Day see excess human beings as the Earth's virus and try to e ...
- UVA 11732 strcmp() Anyone (Trie+链表)
先两两比较,比较次数是两者相同的最长前缀长度*2+1,比较特殊的情况是两者完全相同时候比较次数是单词长度*2+2, 两个单词'末尾\0'和'\0'比较一次,s尾部'\0'和循环内'\0'比较一次. 因 ...
- groupadd - 建 立 新 群 组
总览 SYNOPSIS groupadd [-g gid [-o]] [-r] [-f] group 描述 DESCRIPTION groupadd 可 指 定 群 组 名 称 来 建 立 新 的 群 ...
- QT 调试输出格式
Qt调试输出格式: 1,qDebug() << qPrintable(firstNode.nodeName()) << qPrintable(firstNode.nodeVal ...
- ubuntu k8s 命令补全
apt install bash-completion // locate bash_completion source /usr/share/bash-completion/bash_complet ...
- ssh整合思想 Spring与Hibernate的整合ssh整合相关JAR包下载 .MySQLDialect方言解决无法服务器启动自动update创建表问题
除之前的Spring相关包,还有structs2包外,还需要Hibernate的相关包 首先,Spring整合其他持久化层框架的JAR包 spring-orm-4.2.4.RELEASE.jar ( ...