c plus
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
- 递归
```cpp
class Solution {
public:
vector
res; vector inorderTraversal(TreeNode* root) {
} void helper(TreeNode* root) {helper(root);
return res;
}if (root == NULL) return;
helper(root->left);
res.push_back(root->val);
helper(root->right);
};
- 迭代法
思路:每到一个节点 A,因为根的访问在中间,将 A 入栈。然后遍历左子树,接着访问 A,最后遍历右子树。<br />在访问完 A 后,A 就可以出栈了。因为 A 和其左子树都已经访问完成。
```cpp
栈s;
p= root;
while(p || s不空){
while(p){
p入栈;
p = p的左子树;
} //左子树入栈
p = s.top 出栈;
访问p;
p = p的右子树; //右子树入栈
}
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if (!root) return res;
stack<TreeNode* >s;
TreeNode* cur = root;
while(cur || !s.empty()) {
while (cur) { //先根--左 顺序入栈
s.push(cur);
cur = cur->left;
}
cur = s.top(); s.pop(); //左子树出栈,同时也是跟节点
res.push_back(cur->val);
cur = cur->right; //处理右子树
}
return res;
}
};
//前序遍历 根左右
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode *>s;
TreeNode *rt = root;
while (rt || s.size())
{
while (rt) {
res.push_back(rt->val);//先把根节点存结果
s.push(rt->right); //右节点入栈
rt = rt->left; //左节点
}
rt = s.top();s.pop(); //
}
return res;
}
};
更好理解的模板
- 中序遍历 左根右
```cpp
//中序遍历
class Solution {
public:
vector
inorderTraversal(TreeNode* root) {
} };vector<int> res;
if (!root) return res;
stack<TreeNode* >s;
while(root || !s.empty()) {
if (root) {
s.push(root);
root = root->left;
}else { //说明到达栈顶了,树底。因为上面的root->left为空了。
root = s.top(); s.pop();
res.push_back(root->val); //出栈,处理结果
root = root->right; //把右子树入栈
}
}
return res;
//前序遍历 只改变了一下处理结果时的位置
class Solution {
public:
vector
//后序遍历 左右根
class Solution {
public:
vector
s.pop(); //如果右子树非空,则处理当前节点,并标记
res.push_back(cur->val);
last = cur; //记录已经遍历过的几点,防止死循环。
}
}
}
return res;
}
};
```