Python程序:查找二叉树中仅有单个子节点的节点数
假设我们有一个二叉树;我们需要找到只有单个子节点的节点数量。众所周知,当节点x的父节点只有一个子节点x时,节点x被称为仅有单个子节点的节点。
例如,输入:

则输出为2,因为8和6是仅有单个子节点的节点。
为了解决这个问题,我们将遵循以下步骤:
- 如果根节点为空,则
- 返回0
- d := 一个双端队列
- 将根节点插入到d的末尾
- count := 0
- 当d不为空时,执行:
- current := d的左端元素,并删除左端元素
- 如果current的左子节点不为空,则
- 将current的左子节点插入到d中
- 如果current的右子节点为空,则
- count := count + 1
- 如果current的右子节点不为空,则
- 将current的右子节点插入到d中
- 如果current的左子节点为空,则
- count := count + 1
- 返回count
让我们来看下面的实现以更好地理解。
示例代码
from collections import deque class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right class Solution: def solve(self, root): if not root: return 0 d = deque() d.append(root) count = 0 while d: current = d.popleft() if current.left: d.append(current.left) if not current.right: count += 1 if current.right: d.append(current.right) if not current.left: count += 1 return count ob = Solution() root = TreeNode(9) root.left = TreeNode(7) root.right = TreeNode(10) root.left.right = TreeNode(8) root.right.right = TreeNode(6) print(ob.solve(root))
输入
root = TreeNode(9)root.left = TreeNode(7)
root.right = TreeNode(10)
root.left.right = TreeNode(8)
root.right.right = TreeNode(6)
输出
2
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP