使用 Python 刪除二叉樹中僅有一個子節點的所有節點的程式?
假設我們有一棵二叉樹 root,我們必須刪除僅有一個子節點的所有節點。
因此,如果輸入類似於
則輸出將為
為解決這個問題,我們將遵循以下步驟
定義一個名為 solve() 的方法,它將獲取樹根
如果根為 null,則
返回根
如果根的左節點為 null 且根的右節點為 null,則
返回根
如果根的左節點為 null,則
返回 solve(根的右節點)
如果根的右節點為 null,則
返回 solve(根的左節點)
根的左節點 := solve(根的左節點)
根的右節點 := solve(根的右節點)
返回根
範例
class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def print_tree(root): if root is not None: print_tree(root.left) print(root.data, end = ', ') print_tree(root.right) class Solution: def solve(self, root): if not root: return root if not root.left and not root.right: return root if not root.left: return self.solve(root.right) if not root.right: return self.solve(root.left) root.left = self.solve(root.left) root.right = self.solve(root.right) return root ob = Solution() root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.right.right = TreeNode(5) root.left.left.right = TreeNode(6) root.right.right.left = TreeNode(7) root.right.right.right = TreeNode(8) res = ob.solve(root) print_tree(res)
輸入
root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.right.right = TreeNode(5) root.left.left.right = TreeNode(6) root.right.right.left = TreeNode(7) root.right.right.right = TreeNode(8)
輸出
6, 1, 7, 5, 8,
廣告