mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Update
This commit is contained in:
@ -177,9 +177,7 @@ public:
|
||||
|
||||
```
|
||||
|
||||
那么后序遍历呢
|
||||
|
||||
先序遍历是中左右,后续遍历是左右中,那么我们只需要调整一下先序遍历的代码顺序,就变成中右左的遍历顺序
|
||||
再来看后序遍历,先序遍历是中左右,后续遍历是左右中,那么我们只需要调整一下先序遍历的代码顺序,就变成中右左的遍历顺序
|
||||
,然后在反转result数组,输出的结果顺序就是左右中了,如下图:
|
||||

|
||||
|
||||
@ -208,8 +206,52 @@ public:
|
||||
|
||||
```
|
||||
|
||||
此时我们实现了前后中遍历的三种迭代法,是不是发现迭代法实现的先中后序,其实风格也不是那么统一,除了先序和后序,有关联,中序完全就是另一个风格了,一会用栈遍历,一会又用指针来遍历。
|
||||
|
||||
重头戏来了,接下来介绍一下统一写法。
|
||||
|
||||
#### 迭代法统一写法
|
||||
|
||||
我们以中序遍历为例,之前说使用栈的话,**无法同时解决处理过程和访问过程不一致的情况**,那我们就将访问的节点放入栈中,把要处理的节点也放入栈中但是要做标记,标记就是要处理的节点放入栈之后,紧接着放入一个空指针作为标记。
|
||||
|
||||
代码如下:
|
||||
```
|
||||
class Solution {
|
||||
public:
|
||||
vector<int> inorderTraversal(TreeNode* root) {
|
||||
vector<int> result;
|
||||
stack<TreeNode*> st;
|
||||
if (root != NULL) st.push(root);
|
||||
while (!st.empty()) {
|
||||
TreeNode* node = st.top();
|
||||
if (node != NULL) {
|
||||
st.pop(); // 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
|
||||
if (node->right) st.push(node->right); // 添加右节点
|
||||
|
||||
st.push(node); // 添加中节点
|
||||
st.push(NULL); // 中节点访问过,但是还没有处理,需要做一下标记。
|
||||
|
||||
if (node->left) st.push(node->left); // 添加左节点
|
||||
} else {
|
||||
st.pop(); // 将空节点弹出
|
||||
node = st.top(); // 重新取出栈中元素
|
||||
st.pop();
|
||||
result.push_back(node->val); // 加入到数组中
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
看代码有点抽象我们来看一下动画:
|
||||
|
||||
<video src='../video/中序遍历迭代(统一写法).mp4' controls='controls' width='640' height='320' autoplay='autoplay'> Your browser does not support the video tag.</video></div>
|
||||
|
||||
|
||||
大家在看一下具体代码实现
|
||||
|
||||
接下来给大家介绍一种统一的写法。
|
||||
|
||||
我们再来看一下代码。
|
||||
## C++代码
|
||||
|
Reference in New Issue
Block a user