好东东。灵感来源于线索二叉树
/**
* Definition for binary tree
* 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) {
TreeNode* prev = NULL;
TreeNode* cur = root;
vector<int> ans;
if(root == NULL) {
return ans;
}
while(cur) {
if(cur->left == NULL) {
ans.push_back(cur->val);
cur = cur->right;
} else {
prev = cur->left;
while(prev->right != NULL && prev->right != cur) {
prev = prev->right;
}
if(prev->right == NULL) {
prev->right = cur;
cur = cur->left;
} else {
prev->right = NULL;
ans.push_back(cur->val);
cur = cur->right;
}
}
}
return ans;
}
};
Preorder:
#include <stdio.h>
#include <vector>
using namespace std;
// Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void visit(TreeNode* cur) {
if(cur != NULL) {
printf("%d\n",cur->val);
}
}
void preOrderTravelBT(TreeNode* root) {
TreeNode* cur = root;
TreeNode* pre = NULL;
if(root == NULL) {
return;
}
while(cur) {
if(cur->left == NULL) {
visit(cur);
cur = cur->right;
} else {
pre = cur->left;
while(pre->right != NULL && pre->right != cur) {
pre = pre->right;
}
if(pre->right == NULL) {
pre->right = cur;
visit(cur);
cur = cur->left;
} else {
pre->right = NULL;
cur = cur->right;
}
}
}
}
};
int main(int argc, char *argv[])
{
Solution s;
TreeNode* t9 = new TreeNode(9);
TreeNode* t7 = new TreeNode(7);
t7->left = t9;
TreeNode* t8 = new TreeNode(8);
TreeNode* t6 = new TreeNode(6);
t6->right = t7;
TreeNode* t5 = new TreeNode(5);
t5->left = t8;
TreeNode* t4 = new TreeNode(4);
TreeNode* t3 = new TreeNode(3);
t3->right = t6;
TreeNode* t2 = new TreeNode(2);
t2->left = t4;
t2->right = t5;
TreeNode* t1 = new TreeNode(1);
t1->left = t2;
t1->right = t3;
TreeNode* t10 = new TreeNode(10);
t8->right = t10;
s.preOrderTravelBT(t1);
return 0;
}