</pre><pre name="code" class="cpp">/**中序遍历
* 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;
p=root;
vector<int> a;
stack<TreeNode *> s;
if(root==NULL) return a;
while(!s.empty()||p!=NULL)
{
while(p!=NULL)
{
s.push(p);
p=p->left;//找到树最左边的叶子,这时的p相当于根节点
}
p=s.top();
a.push_back(p->val);//输出
s.pop();//弹出
p=p->right;//根节点访问完了,访问右孩子
}
return a;
}
};
/*vector<int> ret;
stack<TreeNode *> s;
TreeNode *temp = root;
while (!s.empty() || temp != NULL)
{
while (temp != NULL)
{
s.push(temp);
temp = temp->left;
}
temp = s.top();
ret.push_back(temp->val);
s.pop();
temp = temp->right;
}
return ret;
}
Leecode笔记-中序遍历
最新推荐文章于 2022-08-11 21:50:01 发布