題目描述:
Given a binary tree, return the preorder traversal of its nodes' values.
Note: Recursive solution is trivial, could you do it iteratively?
實作思路:
要實作非遞歸的二叉樹前序周遊,可以借助棧來實作,前序周遊是根-左-右,先把根壓棧然後彈出到vector中,再依次将右孩子壓棧、左孩子壓棧,然後疊代進行,每次都彈出棧底的結點~
具體實作:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
vector<int> res;
if(!root){
return res;
}
stack<TreeNode *> st;
st.push(root);
while(st.size()){
TreeNode * temp;
temp = st.top();
res.push_back(temp->val);
st.pop();
if(temp->right){
st.push(temp->right);
}
if(temp->left){
st.push(temp->left);
}
}
return res;
}
};