面试题34:二叉搜索树的后序遍历序列
- 题目描述:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
- 详细代码:
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if not sequence or len(sequence) < 0:
return False
length = len(sequence)
root = sequence[length - 1]
i = 0
for node in range(length - 1):
if root < sequence[node]:
break
i += 1
for j in range(i, length - 1):
if root > sequence[j]:
return False
left = True
if i > 0:
self.VerifySquenceOfBST(sequence[:i])
right = True
if i < length - 1:
self.VerifySquenceOfBST(sequence[i:length -1])
return left and right
面试题34:二叉树中和为某一值的路径
- 题目描述:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
- 详细代码:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
if not root:
return []
res = []
self.FindPathCore(root, expectNumber, [], 0, res)
return res
def FindPathCore(self, root, expectNumber, path, curSum, res):
curSum += root.val
path.append(root)
isLeaf = (root.left == None and root.right == None)
if isLeaf and curSum == expectNumber:
onePath = []
for node in path:
onePath.append(node.val)
res.append(onePath)
if curSum < expectNumber:
if root.left:
self.FindPathCore(root.left, expectNumber, path, curSum, res)
if root.right:
self.FindPathCore(root.right, expectNumber, path, curSum, res)
path.pop()