Previously I did the preorder traversal the same way as inorder traversal, however, there is a more simplified way to do that.
vector<int>preorderTraversal(TreeNode *root) { vector<int> ret; if(!root) return ret; stack s; s.push(root); while(!s.empty()){ TreeNode* cur = s.top(); s.pop(); ret.push_back(cur->val); if(cur->right) s.push(cur->right); if(cur->left) s.push(cur->left); } return ret; }
No comments:
Post a Comment