|
1 | | -from data_structure.tree.Tree import Tree |
| 1 | +from data_structure.tree.tree import Tree, TreeNode |
| 2 | + |
| 3 | + |
| 4 | +class BinaryTreeNode(TreeNode): |
| 5 | + """ |
| 6 | + 一个二叉树节点 |
| 7 | + """ |
| 8 | + |
| 9 | + def __init__(self, value, left, right): |
| 10 | + self.left = left |
| 11 | + self.right = right |
| 12 | + super().__init__(value, [left, right]) |
2 | 13 |
|
3 | 14 |
|
4 | 15 | class BinaryTree(Tree):
|
5 | 16 | """
|
6 | 17 | 二叉树:基本二叉树的数据结构
|
7 | 18 | """
|
8 | | - def __init__(self, key): |
9 | | - self.key = key |
10 | | - self._r_child = None |
11 | | - self._l_child = None |
12 | | - super().__init__(key=key, children=[self._l_child, self._r_child]) |
13 | | - |
14 | | - @property |
15 | | - def l_child(self): |
16 | | - return self._l_child |
17 | | - |
18 | | - @l_child.setter |
19 | | - def l_child(self, l_child): |
20 | | - if not isinstance(l_child, BinaryTree): return |
21 | | - self._l_child = l_child |
22 | | - self.children = [self.l_child, self.r_child] |
23 | | - |
24 | | - @property |
25 | | - def r_child(self): |
26 | | - return self._r_child |
27 | | - |
28 | | - @r_child.setter |
29 | | - def r_child(self, r_child): |
30 | | - if not isinstance(r_child, BinaryTree): return |
31 | | - self._r_child = r_child |
32 | | - self.children = [self.l_child, self.r_child] |
| 19 | + |
| 20 | + def inorder_traversal_while(self): |
| 21 | + """ |
| 22 | + 二叉树的中序遍历 |
| 23 | + :return: list of node values |
| 24 | + """ |
| 25 | + res = [] |
| 26 | + |
| 27 | + if not self.root: |
| 28 | + return res |
| 29 | + |
| 30 | + stack = [self.root] |
| 31 | + node = self.root.left |
| 32 | + |
| 33 | + while len(stack): |
| 34 | + while node: |
| 35 | + stack.append(node) |
| 36 | + node = node.left |
| 37 | + |
| 38 | + res.append(stack[-1].value) |
| 39 | + |
| 40 | + return res |
0 commit comments