二叉树的前序遍历
思路:小心程序运行栈溢出,用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;
}
};