Skip to content

Commit e96f72c

Browse files
Add files via upload
1 parent 132fce2 commit e96f72c

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
14+
#include<vector>
15+
#include<stack>
16+
using namespace std;
17+
18+
class Solution {
19+
public:
20+
vector<int> preorderTraversal(TreeNode* root) {
21+
vector<int> values;
22+
stack<TreeNode*> treeStack;
23+
if (!root)
24+
return values;
25+
26+
while (root || !treeStack.empty())
27+
{
28+
while (root)
29+
{
30+
values.push_back(root->val);
31+
treeStack.push(root);
32+
root = root->left;
33+
}
34+
35+
if (!treeStack.empty())
36+
{
37+
root = treeStack.top();
38+
treeStack.pop();
39+
40+
root = root->right;
41+
}
42+
}
43+
return values;
44+
}
45+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# 52ms 99.00%
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 preorderTraversal(self, root):
12+
"""
13+
:type root: TreeNode
14+
:rtype: List[int]
15+
"""
16+
values = []
17+
treeStack = []
18+
19+
if (root is None):
20+
return values
21+
while root or len(treeStack) > 0:
22+
while root:
23+
values.append(root.val)
24+
treeStack.append(root)
25+
root = root.left
26+
if len(treeStack) > 0:
27+
root = treeStack.pop()
28+
root = root.right
29+
return values

0 commit comments

Comments
 (0)