Given a binary tree, return the preorder traversal of its nodes' values.
Example
Given:
1
/ \
2 3
/ \
4 5
return [1,2,4,5,3].
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL)
return res;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode *t=s.top();
s.pop();
v.push_back(t->val);
if(t->right) //因为栈是先进后出,所以先放入右结点
s.push(t->right);
if(t->left)
s.push(t->left);
}
return res;
}
};
本文介绍了一种使用栈实现二叉树前序遍历的方法,并提供了一个C++示例程序。该程序通过迭代而非递归的方式实现了二叉树节点的前序遍历。
387

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



