一、见到树结构,最容易想到的就是递归
/**
* 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> inorderTraversal(TreeNode* root) {
vector<int> ans,left,right;
if(root)
ans.push_back(root->val);
else
return ans;
if(root->left)
left=inorderTraversal(root->left);
if(root->right)
right=inorderTraversal(root->right);
ans.insert(ans.begin(),left.begin(),left.end());
ans.insert(ans.end(),right.begin(),right.end());
return ans;
}
};
二、但是题目是强调,尝试不用递归的做法
由于递归是基于栈结构实现的,所以,自然想到用栈来实现非递归的算法:
1.当前结点非空,则将该结点入栈,指针移向其左孩子
2.当前结点为空,说明应该“回头”了,取栈顶元素的值加入容器中,并将指针移向其右孩子
/**
* 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> inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector<int> ans;
while(!s.empty() || root)
{
if(root)
{
s.push(root);
root=root->left;
}
else
{
root=s.top();
s.pop();
ans.push_back(root->val);
root=root->right;
}
}
return ans;
}
};