Skip to content

Commit d6953b3

Browse files
Add files via upload
1 parent 6016e7f commit d6953b3

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// 树的三种序的遍历 后序的非递归形式是最难的
2+
// 0ms 100%
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
#include<vector>
14+
#include<stack>
15+
using namespace std;
16+
17+
class Solution {
18+
public:
19+
vector<int> postorderTraversal(TreeNode* root) {
20+
vector<int> values;
21+
stack<TreeNode*> treeStack;
22+
TreeNode *preNode = 0;
23+
24+
if (!root)
25+
return values;
26+
27+
while(root || !treeStack.empty())
28+
{
29+
while (root)
30+
{
31+
treeStack.push(root);
32+
root = root->left;
33+
}
34+
if (!treeStack.empty())
35+
{
36+
root = treeStack.top();
37+
treeStack.pop();
38+
39+
if (root->right == 0 || root->right == preNode)
40+
{
41+
values.push_back(root->val);
42+
preNode = root;
43+
root = 0;
44+
}
45+
else
46+
{
47+
treeStack.push(root);
48+
root = root->right;
49+
}
50+
}
51+
}
52+
return values;
53+
}
54+
};
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# 56ms 80.13%
2+
3+
# Definition for a binary tree node.
4+
# class TreeNode:
5+
# def __init__(self, x):
6+
# self.val = x
7+
# self.left = None
8+
# self.right = None
9+
10+
class Solution:
11+
def postorderTraversal(self, root):
12+
"""
13+
:type root: TreeNode
14+
:rtype: List[int]
15+
"""
16+
values = []
17+
stack = []
18+
preNode = 0
19+
20+
if (root is None):
21+
return values
22+
23+
while root or len(stack) > 0:
24+
while root:
25+
stack.append(root)
26+
root = root.left
27+
if len(stack) > 0:
28+
root = stack.pop()
29+
if root.right is None or root.right == preNode:
30+
values.append(root.val)
31+
preNode = root;
32+
root = None
33+
else:
34+
stack.append(root)
35+
root = root.right
36+
return values

0 commit comments

Comments
 (0)