题解 | #二叉树的中序遍历#
二叉树的中序遍历
https://www.nowcoder.com/practice/0bf071c135e64ee2a027783b80bf781d
中序遍历 迭代实现
W:
利用栈来存储节点,先一直访问到最左边,遇到空指针弹出,处理中间节点,然后去右子树
N:
叶子节点是两个空节点的中间节点,一开始不能推入根节点,不然会多出一个数
进入循环加入 cur!=nullptr判断
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型vector
*/
vector<int> inorderTraversal(TreeNode* root) {
// write code here
stack<TreeNode*> st;
vector<int> res;
if(!root) return res;
TreeNode* cur=root;
while(cur!=nullptr || !st.empty()){
if(cur){
st.push(cur);
cur=cur->left;
}
else{
cur=st.top();
st.pop();
res.push_back(cur->val);
// cur=st.top(); 不需要提取,在下一次循环指向右子树还是空
//
cur=cur->right;
}
}
return res;
}
};