LC144 Binary Tree Preorder Traversal

递归前序遍历比较简单,非递归则需要用栈来设计遍历方法。

注意有栈为空但还未遍历完整棵树的情况,因此判断条件需要判断tmp是否为NULL

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

 

posted @ 2016-07-28 09:18  vaevaevae  阅读(173)  评论(0编辑  收藏  举报