LeetCode-Binary Tree Preorder Traversal

使用了三种方法对二叉树进行前序遍历,具体可以参考二叉树相关知识点总结

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
46
47
48
49
50
51
52
53
54
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
preorder3(root,result);
return result;
}
private:
void preorder1(TreeNode* root, vector<int>& result){
if(root==nullptr) return;
result.push_back(root->val);
preorder1(root->left,result);
preorder1(root->right,result);
}
void preorder2(TreeNode* root, vector<int>& result){
if(root==nullptr) return;
stack<TreeNode*> s;
TreeNode* n=root;
while(!s.empty() || n!=nullptr){
while(n!=nullptr){
s.push(n);
result.push_back(n->val);
n=n->left;
}
if(!s.empty()){
n=s.top();
s.pop();
n=n->right;
}
}
}
void preorder3(TreeNode* root, vector<int>& result){
if(root==nullptr) return;
stack<TreeNode*> s;
s.push(root);
TreeNode* n;
while(!s.empty()){
n=s.top();
s.pop();
result.push_back(n->val);
if(n->right) s.push(n->right);
if(n->left) s.push(n->left);
}
}
};