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].
思路:迭代方法实现,用一个stack + 一个vector实现
java代码如下:
/**
* 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) {
vector<int> path;
stack<TreeNode*> s;
if(root != NULL){
s.push(root);
while(!s.empty()){
root = s.top();
s.pop();
path.push_back(root->val);
if(root->right != NULL)
s.push(root->right);
if(root->left != NULL)
s.push(root->left);
}
return path;
}
}
};