/**
* 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*>sta;
vector<int>ans;
if(!root)return ans;
auto p=root;
while(p||sta.size())
{
while(p)
{
sta.push(p);//把左孩子全压栈
p=p->left;
}
p=sta.top();
sta.pop();
ans.push_back(p->val);//取栈顶数据
p=p->right;//把栈顶右孩子入栈
}
return ans;
}
};
leetcode 94. 二叉树的中序遍历(栈实现)
最新推荐文章于 2024-08-16 23:03:51 发布