mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
add code2 of iterative solution
This commit is contained in:
parent
9d31289601
commit
f5d96222a0
@ -30,27 +30,53 @@ public:
|
|||||||
```
|
```
|
||||||
|
|
||||||
## 思路二
|
## 思路二
|
||||||
|
### 写法一
|
||||||
``` C++
|
``` C++
|
||||||
class Solution {
|
class Solution {
|
||||||
public:
|
public:
|
||||||
vector<int> inorderTraversal(TreeNode* root) {
|
vector<int> inorderTraversal(TreeNode* root) {
|
||||||
vector<int>res;
|
vector<int>res;
|
||||||
if(!root) return res;
|
|
||||||
stack<TreeNode *>stk;
|
stack<TreeNode *>stk;
|
||||||
TreeNode* p = root;
|
TreeNode* p = root;
|
||||||
while(!stk.empty() || p){
|
while(!stk.empty() || p){
|
||||||
if(p){
|
if(p){ // 左: 一路向左下降
|
||||||
stk.push(p);
|
stk.push(p);
|
||||||
p = p -> left; // 一路向左
|
p = p -> left;
|
||||||
}
|
}
|
||||||
else{
|
else{
|
||||||
p = stk.top();
|
p = stk.top(); // 中: 下降不动了, 访问栈顶元素
|
||||||
stk.pop();
|
stk.pop();
|
||||||
res.push_back(p -> val);
|
res.push_back(p -> val);
|
||||||
p = p -> right;
|
p = p -> right; // 右: 访问右子树
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
### 写法二
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
vector<int> inorderTraversal(TreeNode* root) {
|
||||||
|
vector<int>res;
|
||||||
|
stack<TreeNode*>stk;
|
||||||
|
TreeNode *p = root;
|
||||||
|
|
||||||
|
while(!stk.empty() || p){
|
||||||
|
// 左: 一路向左下降
|
||||||
|
while(p){
|
||||||
|
stk.push(p);
|
||||||
|
p = p -> left;
|
||||||
|
}
|
||||||
|
// 中: 下降不动了, 访问栈顶元素
|
||||||
|
p = stk.top(); stk.pop();
|
||||||
|
res.push_back(p -> val);
|
||||||
|
// 右: 访问右子树
|
||||||
|
p = p -> right;
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
Loading…
Reference in New Issue
Block a user