标签:
思路:小心程序运行栈溢出,用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;
}
};
Binary Tree Preorder Traversal
标签:
原文地址:http://www.cnblogs.com/flyjameschen/p/2afc00fa85d8bef10d50fd962bd07c2e.html