Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 72d4242

Browse files
committedMar 23, 2019
add tree iter
1 parent d0c425e commit 72d4242

File tree

1 file changed

+42
-13
lines changed

1 file changed

+42
-13
lines changed
 

‎BinNode.py

+42-13
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
"""
1212

1313

14-
class BinNode():
14+
class TreeNode():
1515
def __init__(self, val, left=None, right=None):
1616
self.val = val
1717
self.left = left
@@ -49,18 +49,16 @@ def preOrder2(root):
4949
:type root: TreeNode
5050
:rtype: List[int]
5151
"""
52-
result = list()
53-
if root == None:
54-
return result
55-
stack = list()
52+
result = []
53+
stack = []
5654
stack.append(root)
5755
while len(stack) != 0:
58-
top = stack.pop()
59-
if top.right != None:
60-
stack.append(top.right)
61-
if top.left != None:
62-
stack.append(top.left)
63-
result.append(top.val)
56+
node = stack.pop()
57+
if node is None:
58+
continue
59+
result.append(node.val)
60+
stack.append(node.right)
61+
stack.append(node.left)
6462
return result
6563

6664

@@ -86,6 +84,37 @@ def inOrder(root): # 中序
8684
cur = cur.left
8785
node = stack.pop()
8886
res.append(node.val)
89-
if node.right:
90-
cur = node.right
87+
cur = node.right
9188
return res
89+
90+
91+
"""
92+
1
93+
/ \
94+
2 3
95+
/ \ \
96+
4 5 6
97+
- 后序遍历顺序:[4 5 2 6 3 1]
98+
"""
99+
100+
101+
def postOrder(root):
102+
result = []
103+
stack = []
104+
stack.append(root)
105+
while len(stack) != 0:
106+
node = stack.pop()
107+
if node is None:
108+
continue
109+
result.append(node.val)
110+
stack.append(node.left)
111+
stack.append(node.right)
112+
return result[::-1]
113+
114+
115+
if __name__ == "__main__":
116+
t = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),
117+
TreeNode(3, None, TreeNode(6)))
118+
print(preOrder2(t))
119+
print(inOrder(t))
120+
print(postOrder(t))

0 commit comments

Comments
 (0)
Please sign in to comment.