Binary Tree Preorder Traversal
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?
根据返回值,没考虑用递归方法做,采用非递归方法,关于二叉树的各种访问方法,见博客:
http://blog.csdn.net/sjf0115/article/details/8645991
vector<int> postorderTraversal(TreeNode *root) {
vector<int> t;
stack<TreeNode*> s;
TreeNode *tree = root;
while (tree !=NULL || !s.empty()){
if (tree != NULL){
t.push_back(tree->val);
s.push(tree);
tree = tree->left;
}
else{
tree = s.top();
s.pop();
tree = tree->right;
}
}
return t;
}