这是只写了先序遍历的非递归代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int>pre_vec; stack<TreeNode *>pre_stack; TreeNode * NowNode=root; while(NowNode||!pre_stack.empty()) { if(NowNode!=NULL) { pre_stack.push(NowNode); pre_vec.push_back(NowNode->val); NowNode=NowNode->left; } else { NowNode=pre_stack.top(); pre_stack.pop(); NowNode=NowNode->right; } } return pre_vec; } };