前言
1、递归。
2、迭代。
3、待优化。
题目
给定一个二叉树,返回它的中序 遍历。
示例:
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
实现方法
一、递归。
/**
* 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> res;
inOrder(root,res);
return res;
}
void inOrder(TreeNode* root,vector<int>& res){
if(root){
inOrder(root->left,res);
res.push_back(root->val);
inOrder(root->right,res);
}
}
};
二、迭代
/**
* 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> res;
stack<TreeNode*> node;
TreeNode* current=root;
while(current || !node.empty()){
if(current){
node.push(current);
current=current->left;
}else{
current=node.top();
res.push_back(current->val);
node.pop();
current=current->right;
}
}
return res;
}
};