-
Notifications
You must be signed in to change notification settings - Fork 0
/
二叉树专题
45 lines (40 loc) · 979 Bytes
/
二叉树专题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
二叉树的前序遍历:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
非递归:
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: Preorder in vector which contains node values.
*/
vector<int> preorderTraversal(TreeNode *root) {
// write your code here
auto R = root;
//int top = -1;
while((S.empty() == false) || R!= NULL){
if(R != NULL){
result.push_back(R->val);
S.push(R);
R = R->left;
}else{
R = S.top();
S.pop();
R=R->right;
}
}
return result;
}
vector<int> result={};
stack<TreeNode *> S;
};