Python算法之求n个节点不同二叉树个数

yipeiwu_com6年前Python基础

问题

创建一个二叉树

二叉树有限多个节点的集合,这个集合可能是:

空集

由一个根节点,和两棵互不相交的,分别称作左子树和右子树的二叉树组成

创建二叉树:

创建节点

再创建节点之间的关系

Python代码示例

# !/usr/bin/env python
# -*-encoding: utf-8-*-
# author:LiYanwei
# version:0.1
class TreeNode(object):
  def __init__ (self, data, left = None, right = None):
    self.data = data
    self.left = left
    self.right = right
  def __str__(self):
    return str(self.data)
# 节点
A = TreeNode('A')
B = TreeNode('B')
C = TreeNode('C')
D = TreeNode('D')
# 节点间的关系
A.left = B
A.right = C
B.right = D
print B.right

问题

求n个节点不同二叉树个数

1个节点
根节点1 1种
1种二叉树

2个节点
根节点1 左节点1 1种(依照1节点的推断)
根节点1 右节点1 1种(依照1节点的推断)
2种二叉树

3个节点
根节点1 左节点0 右节点2 2种(依照2节点的推断)
根节点1 左节点1 右节点1 1种(依照1节点的推断)
根节点1 左节点2 右节点0 2种(依照2节点的推断)
5种二叉树

4个节点
根节点1 左节点0 右节点3 5种(依照3节点的推断)
根节点1 左节点1 右节点2 2种(依照2节点的推断)
根节点1 左节点2 右节点1 2种(依照2节点的推断)
根节点1 左节点3 右节点0 5种(依照4上面的推断)
共14种二叉树

...

n个节点

递归进行累加

Python代码示例

# !/usr/bin/env python
# -*-encoding: utf-8-*-
# author:LiYanwei
# version:0.1
# 求n个节点不同二叉树个数
def count(n):
  # root : 1
  # left : k
  # right : n - 1- k
  # s = 0
  # if n == 0:
  #   # 空树
  #   return 1
  s = count.cache.get(n, 0)
  if s:
    return s
  for k in xrange(n):
    s += count(k) * count(n - 1 - k)
  count.cache[n] = s
  return s
# 重复计算优化
count.cache = {0 : 1}
print count(100)

总结

以上就是本文关于Python算法之求n个节点不同二叉树个数的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:Python探索之自定义实现线程池python中模块的__all__属性详解等,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Python中pymysql 模块的使用详解

pymysql 模块的使用 一、pymysql的下载和使用 (1)pymysql模块的下载 pip3 install pymysql (2)pymysql的使用 # 实现:使用...

python中subprocess批量执行linux命令

可以执行shell命令的相关模块和函数有: os.system os.spawn os.popen --废弃 popen --废弃 commands --废弃,3....

深入探究Django中的Session与Cookie

前言 Cookie和Session相信对大家来说并不陌生,简单来说,Cookie和Session都是为了记录用户相关信息的方式,最大的区别就是Cookie在客户端记录而Session在服...

python 列表,数组,矩阵两两转换tolist()的实例

通过代码熟悉过程: # -*- coding: utf-8 -*- from numpy import * a1 =[[1,2,3],[4,5,6]] #列表 print('a1 :...

TensorFlow dataset.shuffle、batch、repeat的使用详解

直接看代码例子,有详细注释!! import tensorflow as tf import numpy as np d = np.arange(0,60).reshape([6...