Binary Tree Preorder Traversal

Problem:

Given a binary tree, return the preorder traversal of its nodes' value.

For example:

Given binary tree {1, #, 2, 3},

return [1,2,3]

Note: Recursive solution is trivial, could you do it iteratively?

 1 class Solution {
2 public:
3     vector<int> preorderTraversal(TreeNode *root) {
4         vector<int> result;
5         stack<TreeNode *> stk;
6         TreeNode *p = root;
7         while(p != NULL) {
8             result.push_back(p->val);
9             stk.push(p);
10             p = p->left;
11         }
12
13         while(!stk.empty()) {
14             TreeNode *top = stk.top();
15             if(top->right == NULL) {
16                 stk.pop();
17             } else {
18                 TreeNode *p = top->right;
19                 stk.pop();
20                 while(p != NULL) {
21                     result.push_back(p->val);
22                     stk.push(p);
23                     p = p->left;
24                 }
25             }
26         }
27         return result;
28     }
29 };

posted @ 2014-04-28 21:34  夏目家的猫咪老师  阅读(213)  评论(0编辑  收藏  举报