Binary Tree Preorder Traversal
2015-04-01 10:00 笨笨的老兔子 阅读(116) 评论(0) 编辑 收藏 举报二叉树的前序遍历
思路:小心程序运行栈溢出,用stack模拟
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
stack<TreeNode*> stk;
vector<int> res;
if (root)
stk.push(root);
else
return res;
TreeNode* tmpNode;
while (!stk.empty())
{
tmpNode = stk.top();
res.push_back(tmpNode->val);
stk.pop();
if (tmpNode->right !=NULL){
stk.push(tmpNode->right);
}
if (tmpNode->left != NULL){
stk.push(tmpNode->left);
}
}
return res;
}
};