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