二叉树的最大深度
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.
Note: A leaf is a node with no children.
Example:
3
/ \
9 20
/ \
15 7
Code(By myself):
# 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 (not root):
return 0
leftDepth = self.maxDepth(root.left) + 1
rightDepth = self.maxDepth(root.right) + 1
return max(leftDepth,rightDepth)
Code(others):
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
总结:
递归求解
验证二叉搜索数
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Example:
Input:
2
/ \
1 3
Output: true
Code(By myself):
# 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 isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if (not root):
return True
def maxLeft(lroot):
while lroot.right:
lroot = lroot.right
return lroot.val
def minRight(rroot):
while rroot.left:
rroot = rroot.left
return rroot.val
left = -float('inf')
right = float('inf')
if root.left:
left = maxLeft(root.left)
if root.right:
right = minRight(root.right)
if self.isValidBST(root.left) and self.isValidBST(root.right):
if left < root.val and root.val < right:
return True
else:
return False
else:
return False
Code(others):
class Solution(object):
def validBST(self, root, min, max):
if root == None:
return True
if root.val <= min or root.val >= max:
return False
return self.validBST(root.left, min, root.val) and self.validBST(root.right, root.val, max)
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.validBST(root, -21474836480, 21474836470)
总结:
可以将root.val当成左子树的最大值右子树的最小值
对称二叉树
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Example:
1
/ \
2 2
/ \ / \
3 4 4 3
Code(By myself):
# 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 isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
return self.compare(root.left, root.right)
def compare(self, left, right):
if left == None and right == None:
return True
elif left and right:
return self.compare(left.right, right.left) and self.compare(left.left, right.right) and left.val == right.val
else:
return False
Code(others):
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
q = []
q.append((root.left, root.right))
while q:
l, r = q.pop()
if not l and not r:
continue
if not l and r:
return False
if l and not r:
return False
if l.val != r.val:
return False
q.append((l.left, r.right))
q.append((l.right, r.left))
return True
总结:
- 递归求解
- 利用队列求解
对称二叉树
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
Example:
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Code(By myself):
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
result = []
if root == None:
return result
q = [root]
while q:
p = q
q = []
levelResult = []
while p:
r = p.pop(0)
levelResult.append(r.val)
if r.left:
q.append(r.left)
if r.right:
q.append(r.right)
result.append(levelResult)
return result
Code(others):
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
self.dfs(root, 0, res)
return res
def dfs(self, root, depth, res):
if root == None:
return res
if len(res) < depth+1:
res.append([])
res[depth].append(root.val)
self.dfs(root.left, depth+1, res)
self.dfs(root.right, depth+1, res)
总结:
- 双层循环加队列实现层次遍历
- 添加depth标识符利用递归实现层次遍历
将有序数组转换为二叉搜索树
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
Code(By myself):
# 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 len(nums) == 0:
return None
root = TreeNode(nums[len(nums)//2])
if len(nums) == 1:
return root
else:
root.left = self.sortedArrayToBST(nums[:len(nums)//2])
root.right = self.sortedArrayToBST(nums[len(nums)//2+1:])
return root
Code(others):
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
size = len(nums)
if size == 0:
return None
if size == 1:
return TreeNode(nums[0])
size = size//2
root = TreeNode(nums[size])
root.left = self.sortedArrayToBST(nums[:size])
root.right = self.sortedArrayToBST(nums[size+1:])
return root