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的更多相关文章

  1. [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 ...

  2. [LeetCode] 144. Binary Tree Preorder Traversal 二叉树的先序遍历

    Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...

  3. [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 ...

  4. [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 ...

  5. [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 ...

  6. leetcode 199 :Binary Tree Right Side View

    // 我的代码 package Leetcode; /** * 199. Binary Tree Right Side View * address: https://leetcode.com/pro ...

  7. Leetcode 101 Symmetric Tree 二叉树

    判断一棵树是否自对称 可以回忆我们做过的Leetcode 100 Same Tree 二叉树和Leetcode 226 Invert Binary Tree 二叉树 先可以将左子树进行Invert B ...

  8. 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 ...

  9. (二叉树 递归) leetcode 145. Binary Tree Postorder Traversal

    Given a binary tree, return the postorder traversal of its nodes' values. Example: Input: [1,null,2, ...

随机推荐

  1. Android 第三方库导致jar包冲突解决办法

    这几天的任务是将mapbox的工程合到程序中去,但是合并过程却出现了问题 合并方法: 在app的build.gradle中添加 dependencies { compile ('com.mapbox. ...

  2. pytest+allure2+jenkins环境部署

    1.pycharm安装allure-pytest 2.jenkins -> 系统管理 -> 插件管理 -> 可选插件中过滤Allure,勾选对应插件安装 如下图:  3.安装完插件后 ...

  3. 科学效法自然:微软研究人员测试AI控制的滑翔机

    编者按:正如一颗苹果砸出了万有引力,自然界所有存在的事物和现象都有其科学合理的一面,小小的鸟儿也能够给科学带来丰富的灵感和启示. 最近,微软研究人员从自然出发,研究鸟类能够自由停留在空中的科学原理,并 ...

  4. SQLAlchemy的基本使用

    一.介绍 SQLAlchemy是一种ORM(Object-Relational Mapping)框架,用来将关系型数据库映射到对象上.该框架建立在DB API之上,将类和对象转化成SQL,然后使用AP ...

  5. ajax请求执行完成后再执行其他操作(jQuery.page.js插件使用为例)

    就我们做知,ajax强大之处在于它的异步请求,但是有时候我们需要ajax执行彻底完成之后再执行其他函数或操作 这个时候往往我们用到ajax的回调函数,但是假如你不想或者不能把接下来的操作写在回调函数中 ...

  6. 爬虫2_python2

    # -*- coding: UTF-8 -*- # 正则表达式模块 import re # 获取路径模块 import urllib #时间模块 import time def getHtml(url ...

  7. 点击按钮在表格的某一行下,在添加一行(HTML+JS)

    使用js在指定的tr下添加一个新的一行newTr html代码: <table> <tr> <td>用户名:</td> <td><in ...

  8. mysql 定时任务job

    mysql 定时任务job 1.通过show EVENTS显示当前定义的事件 2.检查event_scheduler状态:SHOW VARIABLES LIKE 'event_scheduler' 3 ...

  9. [转载]matlab图像处理为什么要归一化和如何归一化

    matlab图像处理为什么要归一化和如何归一化,一.为什么归一化1.   基本上归一化思想是利用图像的不变矩寻找一组参数使其能够消除其他变换函数对图像变换的影响.也就是转换成唯一的标准形式以抵抗仿射变 ...

  10. mysql EOF

    mysql shell 执行脚本 #!/bin/bash export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/mysql-5.6/bin:/usr ...