题目要求:完成二叉树的中序遍历。
解题方法:
1.递归。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> v;
if(root==NULL)
return v;
v=inorderTraversal(root->left);
v.push_back(root->val);
vector<int> vr=inorderTraversal(root->right);
for(int i=0;i<vr.size();i++){
v.push_back(vr[i]);
}
return v;
}
};
2.循环的方式(题目要求用循环方式来做)
用栈来保存遍历过的节点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> v;
if(root==NULL)
return v;
stack<TreeNode*> s;
TreeNode* p=root;
while(p){
s.push(p);
p=p->left;
}
while(!s.empty()){
p=s.top();
s.pop();
v.push_back(p->val);
if(p->right){
p=p->right;
while(p){
s.push(p);
p=p->left;
}
}
}
return v;
}
};