题目描述
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3},
1 \ 2 / 3
return[1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
相对二叉树的非递归后序遍历来说,非递归先序遍历实现起来较为简单。无需设置访问标记。
提交时间:2016-09-25
语言:C++
运行时间: <1 ms
占用内存:8568K
状态:答案正确
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
|
/**
* Definition for binary tree
* 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) {
stack<TreeNode*> s;
vector<
int
> v;
while
(root!=NULL || !s.empty()){
while
(root != NULL){
v.push_back(root->val);
s.push(root);
root = root->left;
}
if
(!s.empty()){
root = s.top()->right;
s.pop();
}
}
return
v;
}
};
|