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?
使用栈实现遍历,代码如下:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> tree;
vector<int> ans;
if(!root) return ans;
tree.push(root);
while(tree.size()){
TreeNode* temp=tree.top();
ans.push_back(temp->val);
tree.pop();
if(temp->right)
tree.push(temp->right);
if(temp->left)
tree.push(temp->left);
}
return ans;
}

本文介绍了一种使用栈实现二叉树前序遍历的方法,并提供了详细的C++代码示例。通过迭代而非递归的方式,实现了节点值的前序遍历。
3008

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



