94.二叉树的中序遍历
程序员文章站
2024-01-11 16:29:10
...
迭代算法:
/**
* 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) {
TreeNode* p=root;
stack<TreeNode*> s;
vector<int> v;
while(p||!s.empty())
{
while(p)
{
s.push(p);
p=p->left;
}
if(!s.empty())
{
p=s.top();
s.pop();
v.push_back(p->val);
p=p->right;
}
}
return v;
}
};