/**
* 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> ans;
stack<TreeNode*> is;
while( root ){//寻找左子树
//先序遍历 放这记录ans.push_back(root->val);
is.push(root);
root = root->left;
}
while( !is.empty() ){
TreeNode* t = is.top(); //找毕,弹顶找一次右节点
is.pop();
ans.push_back(t->val);
t = t->right;
while( t ){ //寻找左子树
//先序遍历 放这记录ans.push_back(t->val);
is.push(t);
t = t->left;
}
}
return ans;
}
};
啊啊为什么迭代这么难想啊。
emmmm.....
每一轮,使用栈,保存左子树,当一列左子树保存完毕,弹出栈顶,记录,并寻找一次右节点,循环
下面是递归
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
inorderTraversal(root,ans);
return ans;
}
void inorderTraversal(TreeNode* root,vector<int>& ans ){\
if( !root ) return ;
//先序遍历 放这记录ans.push_back(root->val);
inorderTraversal(root->left,ans);
ans.push_back(root->val);
inorderTraversal(root->right,ans);
}
};