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?
用stack,每次先push right再push left Time/Space O(n) 实现:class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; if(!root) return res; stack<TreeNode*> st; st.push(root); while(!st.empty()){ TreeNode* cur = st.top(); st.pop(); res.push_back(cur->val); if(cur->right) st.push(cur->right); if(cur->left) st.push(cur->left); } return res; } };