Given a binary tree, return the preorder traversal of its nodes 'values.
For example:
Given Binary Tree {1, #, 2, 3 },
1 2 / 3
Return [1, 2, 3].
Note: Recursive solution is trivial, cocould You Do It iteratively?
Idea: Take the top element of the stack, output the element and exit it from the stack. If the right subtree is not empty, add the right subtree to the stack. If the left subtree is not empty, add the left subtree to the stack. Loop until the stack is empty.
1 class Solution { 2 public: 3 vector<int> preorderTraversal( TreeNode *root ) { 4 vector<int> result; 5 if( !root ) { return result; } 6 stack<TreeNode*> nodesStack; 7 nodesStack.push( root ); 8 while( !nodesStack.empty() ) { 9 TreeNode* curr = nodesStack.top();10 nodesStack.pop();11 result.push_back( curr->val );12 if( curr->right ) { nodesStack.push( curr->right ); }13 if( curr->left ) { nodesStack.push( curr->left ); }14 }15 return result;16 }17 };