在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Given a binary tree, return the preorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,2,3] Follow up: Recursive solution is trivial, could you do it iteratively? 方法一:使用迭代(C++) 1 vector<int> preorderTraversal(TreeNode* root) { 2 vector<int> res={}; 3 if(!root) 4 return res; 5 stack<TreeNode*> s; 6 TreeNode* cur=root; 7 while(!s.empty()||cur){ 8 while(cur){ 9 res.push_back(cur->val); 10 s.push(cur); 11 cur=cur->left; 12 } 13 cur=s.top(); 14 s.pop(); 15 cur=cur->right; 16 } 17 return res; 18 } 方法二:使用递归,更简单,但是效率较低 1 void preOrder(TreeNode* root,vector<int>& m){ 2 if(!root) 3 return; 4 m.push_back(root->val); 5 preOrder(root->left,m); 6 preOrder(root->right,m); 7 } 8 9 vector<int> preorderTraversal(TreeNode* root) { 10 vector<int> res={}; 11 if(!root) 12 return res; 13 preOrder(root,res); 14 return res; 15 }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论