题目:Binary Tree Preorder Traversal
二叉树的前序遍历,同样使用栈来解,代码如下:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL),right(NULL) {}
}; vector<int> preorderTraversal(TreeNode *root) //非递归的前序遍历(用栈实现)
{
if (NULL == root) {
cout << "tree is empty!" << endl;
exit();
} TreeNode *pre = root;
//TreeNode *pTemp = pre;
stack<TreeNode *> tree_stack;
vector<int> tree_vector; tree_stack.push(pre);
while (!tree_stack.empty()) {
TreeNode *pTemp = tree_stack.top();
tree_stack.pop(); tree_vector.push_back(pTemp->val);
if (pTemp->right != NULL)
tree_stack.push(pTemp->right);
if (pTemp->left != NULL)
tree_stack.push(pTemp->left);
}
return tree_vector;
}