[LeetCode] 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?

/**
 * 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> result;
         stack<TreeNode*> s;
         TreeNode *p = root;
      while( p!=NULL || !s.empty() )   //第一个结点根左,及左孩子的左遍历
      {
         while(p!=NULL)
         {
             result.push_back(p->val);
             s.push(p);
             p = p->left;
         }
         if(!s.empty())  //将while中所有的根左结点当作根结点,查看右结点,并下一轮while访问右结点的根左
         {
             p = s.top();
             s.pop();
             p = p->right;
         }
      }
        return result;
    }

};

 

posted @ 2014-06-10 08:08  Xylophone  Views(117)  Comments(0Edit  收藏  举报