add code2 of iterative solution

This commit is contained in:
ShusenTang 2020-06-25 18:40:10 +08:00 committed by GitHub
parent 9d31289601
commit f5d96222a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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;
}
};
```