Title: Binary Tree preorder traversal
The stack is also used for the forward traversal of a binary tree. The Code is as follows:
1 struct TreeNode { 2 int val; 3 TreeNode* left; 4 TreeNode* right; 5 TreeNode(int x): val(x), left(NULL),right(NULL) {} 6 }; 7 8 vector<int> preorderTraversal(TreeNode *root) //非递归的前序遍历(用栈实现) 9 {10 if (NULL == root) {11 cout << "tree is empty!" << endl;12 exit(0);13 }14 15 TreeNode *pre = root;16 //TreeNode *pTemp = pre;17 stack<TreeNode *> tree_stack;18 vector<int> tree_vector;19 20 tree_stack.push(pre);21 while (!tree_stack.empty()) {22 TreeNode *pTemp = tree_stack.top();23 tree_stack.pop();24 25 tree_vector.push_back(pTemp->val);26 if (pTemp->right != NULL) 27 tree_stack.push(pTemp->right);28 if (pTemp->left != NULL)29 tree_stack.push(pTemp->left);30 }31 return tree_vector;32 }
Leetcode: Binary Tree preorder traversal