1.二叉树有父节点。
2.非递归不用栈,不能修改树的结构(临时也不行)。
o(n)时间复杂度,o(1)空间复杂度中序遍历二叉树
做法:用一个last指针和一个cur指针。
主要是查看是
0.是否已经回到访问完的根节点
1.从子节点回溯到当前节点
1.1 从左孩子回溯的:访问当前节点
1.2 从右孩子回溯的:已经访问完,应该回到父节点了
2.从父节点过来的
#include <stdio.h>
#include <vector>
using namespace std;
// Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode *parent;
TreeNode(int x) : val(x), left(NULL), right(NULL), parent(NULL) {}
};
class Solution {
public:
void visit(TreeNode* cur) {
if(cur != NULL) {
printf(" %d \n", cur->val);
}
}
void inorderTraversal(TreeNode *root) {
TreeNode* last = NULL;
TreeNode* cur = root;
while(cur) {
if(last == NULL || last == cur->parent) {
//visit left child
while(cur->left) {
last = cur;
cur = cur->left;
}
visit(cur);
if(cur->right) {
last = cur;
cur = cur->right;
} else {
last = cur;
cur = cur->parent;
}
} else if(cur != NULL && last == cur->left) {
visit(cur);
if(cur->right) {
last = cur;
cur = cur->right;
} else {
last = cur;
cur = cur->parent;
}
} else if(cur != NULL && last == cur->right){
last = cur;
cur = cur->parent;
}
}
}
};
int main(int argc, char *argv[])
{
Solution s;
TreeNode* t9 = new TreeNode(9);
TreeNode* t7 = new TreeNode(7);
t7->left = t9;
t9->parent = t7;
TreeNode* t8 = new TreeNode(8);
TreeNode* t6 = new TreeNode(6);
t6->right = t7;
t7->parent = t6;
TreeNode* t5 = new TreeNode(5);
t5->left = t8;
t8->parent = t5;
TreeNode* t4 = new TreeNode(4);
TreeNode* t3 = new TreeNode(3);
t3->right = t6;
t6->parent = t3;
TreeNode* t2 = new TreeNode(2);
t2->left = t4;
t4->parent = t2;
t2->right = t5;
t5->parent = t2;
TreeNode* t1 = new TreeNode(1);
t1->left = t2;
t2->parent = t1;
t1->right = t3;
t3->parent = t1;
s.inorderTraversal(t1);
return 0;
}