94. 二叉树的中序遍历 - 力扣(LeetCode)
代码随想录 (programmercarl.com)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// 递归遍历
class Solution {
public:
void traversal(TreeNode* cur,vector& vec) {
if(cur == NULL) return;
traversal(cur->left,vec);
vec.push_back(cur->val);
traversal(cur->right,vec);
}
vector inorderTraversal(TreeNode* root) {
vector vec;
traversal(root,vec);
return vec;
}
};
// 非递归遍历
class Solution {
public:
vector inorderTraversal(TreeNode* root) {
vector res;
stack st;
TreeNode* cur = root;
while(cur || !st.empty()) {
// 指针来访问节点,访问到最底层
if(cur) {
st.push(cur);// 将访问的节点放进栈
cur = cur->left; // 左
} else {
cur = st.top(); // 从栈里弹出的数据,就是要处理的数据(放进result数组里的数据)
st.pop();
res.push_back(cur->val);
cur = cur->right; // 右
}
}
return res;
}
};
/*
5
4 6
1 2
// 第一步
--------------------------------------------
| 5 4 1
--------------------------------------------
// 第二步
--------------------------------------------
| 5 4
--------------------------------------------
1
// 第三步
--------------------------------------------
| 5 2
--------------------------------------------
1 4
// 第四步
--------------------------------------------
| 5
--------------------------------------------
1 4 2
// 第五步
--------------------------------------------
| 6
--------------------------------------------
1 4 2 5
// 第六步
--------------------------------------------
|
--------------------------------------------
1 4 2 5 6
*/