Leetcode刷题(25) 树的问题
剑指 Offer 68 - II. 二叉树的最近公共祖先
# 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 lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root == None:
return None
if root == p or root == q:
return root
leftparent = self.lowestCommonAncestor(root.left, p, q)
rightparent = self.lowestCommonAncestor(root.right, p, q)
# q和p都不在左子树上
if leftparent == None:
return rightparent
# q和p都不在右子树上
elif rightparent == None:
return leftparent
# 这步才是关键
# 当 left 和 right 同时不为空
# 说明 p,q 分列在 root 的 异侧 (分别在 左 / 右子树),因此 root 为最近公共祖先,返回 root
return root
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
# 利用二叉搜索树的性质(一边大一边小的性质)
class Solution:
def lowestCommonAncestor(self, root, p, q):
while root:
# p,q 都在 root 的右子树中
if root.val < p.val and root.val < q.val:
root = root.right # 遍历至右子节点
# p,q 都在 root 的左子树中
elif root.val > p.val and root.val > q.val:
root = root.left # 遍历至左子节点
# 当遍历的那一边的子树不包含q,p两个点的时候
else: break
return root
230. 二叉搜索树中第K小的元素
二叉搜索树的中序遍历是升序排列!
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# 二叉搜索树的中序遍历是递增序列哦
class Solution(object):
def __init__(self):
self.count = 0
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
if root == None:
return
nodel = self.kthSmallest(root.left, k)
# 一旦发现找到了立即返回答案
self.count += 1
if self.count == k:
return root.val
noder = self.kthSmallest(root.right, k)
# 答案不是在左子树就是在右子树
if nodel != None:
return nodel
else:
return noder
剑指 Offer 54. 二叉搜索树的第k大节点
和上一题的唯一差别就是将对右子树的递归放到左子树的前面(反中序遍历)
# 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 __init__(self):
self.count = 0
def kthLargest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
if root == None:
return
noder = self.kthLargest(root.right, k)
# 一旦发现找到了立即返回答案
self.count += 1
if self.count == k:
return root.val
nodel = self.kthLargest(root.left, k)
# 答案不是在左子树就是在右子树
if nodel != None:
return nodel
else:
return noder
102. 二叉树的层序遍历
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
levels = []
level = 0
queue = collections.deque([])
queue.append(root)
while(len(queue) > 0):
qsize = len(queue)
levels.append([])
for i in range(qsize):
cur = queue.popleft()
levels[level].append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
level += 1
return levels
144. 二叉树的前序遍历
用辅助栈的迭代法
# 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 preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
if not root:
return []
# 将root先放入栈中
# 0: 没有被遍历过; 1: 被遍历过一次
stack = [(0, root)]
while stack:
flag, node = stack.pop()
res.append(node.val)
if node.right:
stack.append((0, node.right))
if node.left:
stack.append((0, node.left))
return res
传统的递归法
# 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 __init__(self):
self.res = []
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
self.res.append(root.val)
self.preorderTraversal(root.left)
self.preorderTraversal(root.right)
return self.res
94. 二叉树的中序遍历
迭代法
# 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 inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
res = []
stack = []
stack.append((0, root))
while stack:
flag, node = stack.pop()
# 跳过为None的node
if flag == 0:
if node.right:
stack.append((0, node.right))
stack.append((flag + 1, node)) # 夹在中间
if node.left:
stack.append((0, node.left))
else: # flag == 1
res.append(node.val)
return res
树的递归法
# 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 __init__(self):
self.res = []
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
self.inorderTraversal(root.left)
self.res.append(root.val)
self.inorderTraversal(root.right)
return self.res
145. 二叉树的后序遍历
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def __init__(self):
self.res = []
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
self.postorderTraversal(root.left)
self.postorderTraversal(root.right)
self.res.append(root.val)
return self.res
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
stack = [(0, root)]
res = []
while len(stack) > 0:
flag, node = stack.pop()
if node == None:
continue
if flag == 0:
stack.append((1, node))
stack.append((0, node.right))
stack.append((0, node.left))
if flag == 1:
res.append(node.val)
return res
剑指Offer_编程题 对称的二叉树
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetrical(self, pRoot):
def recursion(left, right):
if not left and not right:
return True
if not left or not right:
return False
res = bool(left.val == right.val)
return res and recursion(left.left, right.right) and recursion(left.right, right.left)
# write code here
if pRoot == None:
return True
if not pRoot.left and not pRoot.right:
return True
if not pRoot.left or not pRoot.right:
return False
return recursion(pRoot.left, pRoot.right)