leetcode-144-二叉树的前序遍历

时间:2021-07-26 16:32:32   收藏:0   阅读:0

不太明智的c++实现方法:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     vector<int> preorderTraversal(Tre-eNode* root) {
15         vector<int> seq;
16         if(root == nullptr) return seq;
17         TreeNode *p;
18         p=root;
19         stack<TreeNode*> s;
20         s.push(p);
21         while(!s.empty()){
22             p=s.top();
23             seq.push_back(p->val);
24             s.pop();
25             if(p->right != nullptr){
26                 s.push(p->right);
27             }
28             if(p->left != nullptr){
29                 s.push(p->left);
30             }
31         }
32         return seq;
33     }
34 };

 

------------恢复内容结束------------

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!