[Tree]Binary Tree Preorder Traversal
Total Accepted: 97599 Total Submissions: 257736 Difficulty: Medium
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 a binary tree node. * 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> res; TreeNode* p = root; if(p==NULL){ return res; } stack<TreeNode*> stk; while(p || !stk.empty()){ while(p){ res.push_back(p->val); stk.push(p); p=p->left; } if(!stk.empty()){ p = stk.top()->right; stk.pop(); } } return res; } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号