1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution 11 { 12 vector<int> res; 13 public: 14 vector<int> preorderTraversal(TreeNode* root) 15 { 16 if(!root) return res; 17 stack<TreeNode*> s; 18 s.push(root); 19 while(!s.empty()) 20 { 21 root = s.top(); 22 s.pop(); 23 res.push_back(root->val); 24 if(root->right) s.push(root->right); 25 if(root->left) s.push(root->left); 26 } 27 return res; 28 } 29 };
原文地址:https://www.cnblogs.com/yuhong1103/p/12622351.html
时间: 2024-11-03 13:09:48