二叉树的中序遍历
/**
* 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:
void get_res(vector<int>& res, TreeNode* root) //递归求解
{
if(root == NULL)
return;
get_res(res,root->left);
res.push_back(root->val);
get_res(res,root->right);
return;
}
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> temp;
TreeNode* now;
now = root;
while(now != NULL || !temp.empty()) //非递归求解
{
while(now != NULL) //有左子则一直向下
{
temp.push(now);
now = now->left;
}
now = temp.top();//无左子则开始从当前节点输出并回溯
temp.pop();
res.push_back(now->val);
now = now->right; //输出父节点后处理右子树
}
//get_res(res, root);
return res;
}
};