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> result;
inorderTraversal(result,root);
return result;
}
void inorderTraversal(vector<int>& result,TreeNode* root){
if(root==NULL) return ;
if(root->left!=NULL) inorderTraversal(result,root->left);
result.push_back(root->val);
if(root->right!=NULL) inorderTraversal(result,root->right);
}
};
2.循环
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
inorderTraversalLiter(result,root);
return result;
}
void inorderTraversalLiter(vector<int>& result,TreeNode* root){
if(!root) return;
TreeNode *cursor,*pre;
pre=cursor = root;
while(cursor){
if(!cursor->left){
result.push_back(cursor->val);
cursor=cursor->right;
}else{
pre = cursor->left;
while(pre->right && pre->right != cursor) pre = pre->right;
if(!pre->right){
pre->right = cursor;
cursor = cursor->left;
}else{
pre->right = NULL;
result.push_back(cursor->val);
cursor = cursor->right;
}
}
}
}
};