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, could you do it iteratively?
/**
* 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> results;
vector<int> preorderTraversal(TreeNode *root) {
if(root == NULL) return results;
stack<TreeNode *> st;
while(root != NULL) {
results.push_back(root->val);
st.push(root);
root = root->left;
}
while(!st.empty()) {
TreeNode *top = st.top();
st.pop();
if(top->right != NULL) {
TreeNode* temp = top->right;
results.push_back(temp->val);
st.push(temp);
temp = temp->left;
while(temp != NULL) {
results.push_back(temp->val);
st.push(temp);
temp = temp->left;
}
}
}
return results;
}
};
本文介绍了一种不使用递归的二叉树前序遍历算法实现,通过栈来辅助完成节点值的收集。具体步骤包括:首先将根节点的值加入结果向量,并将根节点压入栈中;随后不断处理当前节点的左子树直至为空,过程中继续收集节点值并压栈;最后再处理栈内元素及其右子树。
1177

被折叠的 条评论
为什么被折叠?



