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, ...
随机推荐
- ios 根据字典自动生成属性
- (void)createPropertyCode{ NSMutableString *codes = [NSMutableString string]; // 遍历字典 [self enumera ...
- ajax提交表单无法验证easyui的验证选项(比如required等)
在实际开发中,遇到ajax方式提交表单没法验证easyui的验证选项,这对实际用户体验造成了很大的困扰.当然,这也是理所当然的事情. 解决办法:使用jquery中ajax的beforeSend事件 ...
- python+selenium之断言Assertion
一.断言方法 断言是对自动化测试异常情况的判断. # -*- coding: utf-8 -*- from selenium import webdriver import unittest impo ...
- jsp之数据提交与获取(传统方法)
package com.java.model; public class Student { private String name; private int age; public String g ...
- javaweb基础(10)_HttpServletRequest原理介绍
一.HttpServletRequest介绍 HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,通过这个对象 ...
- HTML5<nav>元素
HTML5中<nav>元素定义页面导航链接的部分区域,但并不是所有的链接都放到nav元素里面. 实例: <header id="pageHeader"> & ...
- vs 2012打开vs2013的sln
Project -> Properties -> General -> Platform Toolset (as IInspectable correctly commented)
- 用promise封装ajax
首先贴代码 var ajaxOptions = { url: 'url', method: 'GET', async: true, data: null, dataType: 'text', } fu ...
- TypeError: Cannot read property 'tap' of undefined
E:\vue-project\vue-element-admin-master>npm run build:prod vue-element-admin@3.8.1 build:prod E:\ ...
- PAT 乙级 1086
题目 题目地址:PAT 乙级 1086 思路 本题比较简单,但还是存在小小的坑点,简单说一下: 倒置中需要注意的唯一问题就是:100倒置后不是001,而是1:这个问题处理之后还要注意另一个点就是,10 ...