この記事では、Python でバイナリ ツリーを実装するためのアルゴリズムの例をいくつか紹介します。一定の参考値があります。必要な友人は参照してください。お役に立てば幸いです。
ノード定義
class Node(object): def __init__(self, left_child, right_child, value): self._left_child = left_child self._right_child = right_child self._value = value @property def left_child(self): return self._left_child @property def right_child(self): return self._right_child @left_child.setter def left_child(self, value): self._left_child = value @right_child.setter def right_child(self, value): self._right_child = value @property def value(self): return self._value @value.setter def value(self, value): self._value = value
バイナリ ツリー定義
class Tree(object): def __init__(self, value): self._root = Node(None, None, value=value) @property def root(self): return self._root
プリオーダー トラバーサル
再帰的メソッド
''' 先序遍历,递归方式 ''' def preoder(root): if not isinstance(root, Node): return None preorder_res = [] if root: preorder_res.append(root.value) preorder_res += preoder(root.left_child) preorder_res += preoder(root.right_child) return preorder_res
Non-再帰的メソッド
''' 先序遍历,非递归方式 ''' def pre_order_not_recursion(root): if not isinstance(root, Node): return None stack = [root] result = [] while stack: node = stack.pop(-1) if node: result.append(node.value) stack.append(node.right_child) stack.append(node.left_child) return result
順序トラバーサル
再帰的メソッド
''' 中序遍历,递归方式 ''' def middle_order(root): if not isinstance(root, Node): return None middle_res = [] if root: middle_res += middle_order(root.left_child) middle_res.append(root.value) middle_res += middle_order(root.right_child) return middle_res
非再帰的メソッド
''' 中序遍历,非递归方式 ''' def middle_order_bot_recursion(root): if not isinstance(root, Node): return None result = [] stack = [root.right_child, root.value, root.left_child] while stack: temp = stack.pop(-1) if temp: if isinstance(temp, Node): stack.append(temp.right_child) stack.append(temp.value) stack.append(temp.left_child) else: result.append(temp) return result
後順トラバーサル
再帰的メソッド
''' 后序遍历,递归方式 ''' def post_order(root): if not isinstance(root, Node): return None post_res = [] if root: post_res += post_order(root.left_child) post_res += post_order(root.right_child) post_res.append(root.value) return post_res
非再帰メソッド
''' 后序遍历,非递归方式 ''' def post_order_not_recursion(root): if not isinstance(root, Node): return None stack = [root.value, root.right_child, root.left_child] result = [] while stack: temp_node = stack.pop(-1) if temp_node: if isinstance(temp_node, Node): stack.append(temp_node.value) stack.append(temp_node.right_child) stack.append(temp_node.left_child) else: result.append(temp_node) return result
階層トラバーサル
''' 分层遍历,使用队列实现 ''' def layer_order(root): if not isinstance(root, Node): return None queue = [root.value, root.left_child, root.right_child] result = [] while queue: temp = queue.pop(0) if temp: if isinstance(temp, Node): queue.append(temp.value) queue.append(temp.left_child) queue.append(temp.right_child) else: result.append(temp) return result
二分木のノード数を計算する
''' 计算二叉树结点个数,递归方式 NodeCount(root) = NodeCount(root.left_child) + NodeCount(root.right_child) ''' def node_count(root): if root and not isinstance(root, Node): return None if root: return node_count(root.left_child) + node_count(root.right_child) + 1 else: return 0 ''' 计算二叉树结点个数,非递归方式 借用分层遍历计算 ''' def node_count_not_recursion(root): if root and not isinstance(root, Node): return None return len(layer_order(root))
二分木の深さを計算する
''' 计算二叉树深度,递归方式 tree_deep(root) = 1 + max(tree_deep(root.left_child), tree_deep(root.right_child)) ''' def tree_deep(root): if root and not isinstance(root, Node): return None if root: return 1 + max(tree_deep(root.left_child), tree_deep(root.right_child)) else: return 0 ''' 计算二叉树深度,非递归方法 同理参考分层遍历的思想 ''' def tree_deep_not_recursion(root): if root and not isinstance(root, Node): return None result = 0 queue = [(root, 1)] while queue: temp_node, temp_layer = queue.pop(0) if temp_node: queue.append((temp_node.left_child, temp_layer+1)) queue.append((temp_node.right_child, temp_layer+1)) result = temp_layer + 1 return result-1
二分木のノード数を計算する k-レベルノードの数
''' 计算二叉树第k层节点个数,递归方式 kth_node_count(root, k) = kth_node_count(root.left_count, k-1) + kth_node_count(root.right_count, k-1) ''' def kth_node_count(root, k): if root and not isinstance(root, Node): return None if not root or k k: return result else: queue.append((temp_node.left_child, temp_layer+1)) queue.append((temp_node.right_child, temp_layer+1)) return result
二分木の葉ノード数を計算する
''' 计算二叉树叶子节点个数,递归方式 关键点是叶子节点的判断标准,左右孩子皆为None ''' def leaf_count(root): if root and not isinstance(root, Node): return None if not root: return 0 if not root.left_child and not root.right_child: return 1 return leaf_count(root.left_child) + leaf_count(root.right_child)
2つの二分木が正しいかどうかを判断します同じ
''' 判断两个二叉树是不是相同,递归方式 isSame(root1, root2) = (root1.value == root2.value) and isSame(root1.left, root2.left) and isSame(root1.right, root2.right) ''' def is_same_tree(root1, root2): if not root1 and not root2: return True if root1 and root2: return (root1.value == root2.value) and \ is_same_tree(root1.left_child, root2.left_child) and \ is_same_tree(root1.right_child, root2.right_child) else: return False
二分探索木BSTかどうかの判定
''' 判断是否为二分查找树BST,递归方式 二分查找树的定义搞清楚,二分查找树的中序遍历结果为递增序列 ''' def is_bst_tree(root): if root and not isinstance(root, Node): return None def is_asc(order): for i in range(len(order)-1): if order[i] > order[i+1]: return False return True return is_asc(middle_order_bot_recursion(root))
テスト方法
if __name__ == "__main__": tree = Tree(1) tree1 = Tree(1) node6 = Node(None, None, 7) node5 = Node(None, None, 6) node4 = Node(None, None, 5) node3 = Node(None, None, 4) node2 = Node(node5, node6, 3) node1 = Node(node3, node4, 2) tree.root.left_child = node1 tree.root.right_child = node2 tree1.root.left_child = node2 tree1.root.right_child = node2 print(is_bst_tree(tree.root))
以上がバイナリ ツリー アルゴリズムの Python 実装例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Numpyを使用して多次元配列を作成すると、次の手順を通じて実現できます。1)numpy.array()関数を使用して、np.array([[1,2,3]、[4,5,6]])などの配列を作成して2D配列を作成します。 2)np.zeros()、np.ones()、np.random.random()およびその他の関数を使用して、特定の値で満たされた配列を作成します。 3)アレイの形状とサイズの特性を理解して、サブアレイの長さが一貫していることを確認し、エラーを回避します。 4)np.reshape()関数を使用して、配列の形状を変更します。 5)コードが明確で効率的であることを確認するために、メモリの使用に注意してください。

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Forpythondatastorage、chooseLists forfficability withmixeddatypes、array.arrayformemory-efficienthogeneousnumericaldata、およびnumpyArrays foradvancednumericalcomputing.listSareversatilebuteficient efficient forlargeNumericaldatates;

pythonlistsarebetterthanarrays formangingdiversedatypes.1)listscanholdelementsofdifferenttypes、2)adearedditionsandremovals、3)theeofferintutiveoperation likeslicing、but4)theearlessememory-effice-hemory-hemory-hemory-hemory-hemory-adlower-dslorededatas。

toaccesselementsinapythonarray、useindexing:my_array [2] Accessesthirderement、Returning3.pythonuseszero basedIndexing.1)usepositiveandnegativeindexing:my_list [0] forteefirstelement、my_list [-1] exterarast.2)

記事では、構文のあいまいさのためにPythonにおけるタプル理解の不可能性について説明します。 Tupple式を使用してTuple()を使用するなどの代替は、Tuppleを効率的に作成するためにお勧めします。(159文字)

この記事では、Pythonのモジュールとパッケージ、その違い、および使用について説明しています。モジュールは単一のファイルであり、パッケージは__init__.pyファイルを備えたディレクトリであり、関連するモジュールを階層的に整理します。

記事では、PythonのDocstrings、それらの使用、および利点について説明します。主な問題:コードのドキュメントとアクセシビリティに関するドキュストリングの重要性。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

ホットトピック









