-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path144.二叉树的前序遍历.cpp
More file actions
38 lines (35 loc) · 877 Bytes
/
144.二叉树的前序遍历.cpp
File metadata and controls
38 lines (35 loc) · 877 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
/*
* @lc app=leetcode.cn id=144 lang=cpp
*
* [144] 二叉树的前序遍历
*/
// @lc code=start
/**
* 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 = *new vector<int>;
TreeNode* move = root;
stack<TreeNode*> heap; // 堆栈。
while (!heap.empty() || move){
while (move){
heap.push(move);
result.push_back(move->val); //
move = move->left;
}
move = heap.top()->right;
heap.pop();
}
return result;
}
};
// @lc code=end