算法导论第二版习题10.4-5.非递归有父节点中序遍历二叉树

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值