LeetCode-Binary Tree Preorder Traversal[二叉树]

 1 #include<iostream>
 2 #include<vector>
 3 #include<stack>
 4 using namespace std;
 5 
 6 class Solution
 7 {
 8 public:
 9     vector<int> preorderTraversal(TreeNode *root)
10     {
11         vector<int> result;
12         const TreeNode *p;
13         stack<const TreeNode *> s;
14 
15         p = root;
16         if(p != nullptr)    s.push(p);
17         while(!s.empty())
18         {
19             p = s.top();
20             s.pop();
21             result.push_back(p->val);
22 
23             if(p->right != nullptr)    s.push(p->right);
24             if(p->left != nullptr)    s.push(p->left);    //stack 后进先出 所以先判断right
25         }
26         return result;
27     }
28 }

 

posted @ 2016-05-25 20:33  你眉目~依如画  阅读(154)  评论(0编辑  收藏  举报