leetcode 94 中序遍历模板
/**递归的写法 * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ void MiddleTravel(TreeNode * root,vector<int>&result_vec) { if(root!=NULL) { MiddleTravel(root->left,result_vec); result_vec.push_back(root->val); MiddleTravel(root->right,result_vec); } } class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int>result_vec; MiddleTravel(root,result_vec); return result_vec; } };
下面是一个不用递归的写法,用栈:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> inorderTraversal(TreeNode* root) { 13 vector<int>result_vec; 14 stack<TreeNode *>q_stack; 15 TreeNode *NowNode=root; 16 while(NowNode||!q_stack.empty()) { 17 if(NowNode!=NULL) { 18 q_stack.push(NowNode); 19 NowNode=NowNode->left; 20 } 21 else { 22 NowNode=q_stack.top(); 23 result_vec.push_back(NowNode->val); 24 q_stack.pop(); 25 NowNode=NowNode->right; 26 } 27 } 28 return result_vec; 29 } 30 };