6.19
我说15周怎么这么长...原来忘记新开一篇了...sigh 0-0
leetcode 144 Binary Tree Preorder Traversal
二叉树的前序遍历,非递归实现
1 class Solution{ 2 public: 3 vector<int> preorderTraversal(TreeNode* root){ 4 vector<int> ans; 5 stack<TreeNode*> s; 6 if(root == NULL) return ans; 7 else{ 8 s.push(root); 9 while(!s.empty()){ 10 TreeNode* tmp = s.top();s.pop(); 11 ans.push_back(tmp->val); 12 if(tmp->right != NULL) s.push(tmp->right); 13 if(tmp->left != NULL) s.push(tmp->left); 14 } 15 return ans; 16 } 17 } 18 };
时间: 2024-10-17 20:18:57