Given a binary tree, returnPreorderTraversal 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?
Question
The binary tree is first traversed sequentially. The recursive idea is common. Can we use iteration?
Non-recursive approach: <using Stack>
vector<int> preorderTraversal(TreeNode *root) { stack<TreeNode* > st; vector<int> vi; vi.clear(); if(!root) return vi; st.push(root); while(!st.empty()){ TreeNode *tmp = st.top(); vi.push_back(tmp->val); st.pop(); if(tmp->right) st.push(tmp->right); if(tmp->left) st.push(tmp->left); } return vi; }
Recursive thinking:
class Solution {private: vector<int> vi;public: vector<int> preorderTraversal(TreeNode *root) { vi.clear(); if(!root) return vi; preorder(root);return vi; } void preorder(TreeNode* root){ if(!root) return; vi.push_back(root->val); preorder(root->left); preorder(root->right); }};
-------------------------------------------------
|
Double_win Source: http://www.cnblogs.com/double-win/p/3895822.html Disclaimer: Due to my limited level, if there is anything wrong with the expression and code in the article, please criticize and correct it ~ |