遍历二叉树,利用栈和只用固定存储空间,递归和非递归。

	struct BinaryTreeDate
	{
		BinaryTreeDate *parent;
		BinaryTreeDate *left;
		int key;
		BinaryTreeDate *right;
		BinaryTreeDate(int Key) :key(Key), left(nullptr), right(nullptr), parent(nullptr){}
	};

	void Display(BinaryTreeDate *Node)
	{
		if (Node == nullptr)
			return;

		Display(Node->left);
		Display(Node->right);
		cout << Node->key << endl;
	}

	void Display1(BinaryTreeDate *Node)
	{
		stack<BinaryTreeDate *> Val, st;
		st.push(Node);

		while (!st.empty())
		{
			BinaryTreeDate *T = st.top()->left;
			while (T != nullptr && T != Val.top())
			{
				st.push(T);
				T = T->left;
			}

			T = st.top()->right;
			while (T != nullptr && T != Val.top())
			{
				st.push(T);
				T = T->right;
			}
			Val.push(st.top());
			st.pop();
		}
		while (!Val.empty())
		{
			cout << Val.top()->key << endl;
			Val.pop();
		}
	}

	void Display2(BinaryTreeDate *Node)
	{
		stack<BinaryTreeDate *> st;
		BinaryTreeDate *Left = Node;
		BinaryTreeDate *Right = Node;
		st.push(Node);
		while (!st.empty())
		{
			cout << st.top()->key << endl;
			Left = st.top()->left;
			Right = st.top()->right;
			st.pop();
			if (Left != nullptr)
				st.push(Left);
			if (Right != nullptr)
				st.push(Right);
		}
	}

	void Fun(BinaryTreeDate * &Root)
	{
		while (Root->left != nullptr || Root->right != nullptr)
		{
			while (Root->left != nullptr)
				Root = Root->left;

			while (Root->right != nullptr)
				Root = Root->right;
		}
	}

	void Display3(BinaryTreeDate *Node)
	{
		BinaryTreeDate *Root = Node;
		cout << Node->key << endl;
		Fun(Root);
		while (Root != Node)
		{
			if (Root != Root->parent->right )
			{
				if (Root->parent->right != nullptr)
				{
					cout << Root->key << endl;
					Root = Root->parent->right;
					Fun(Root);
				}
				else
				{
					cout << Root->key << endl;
					Root = Root->parent;
				}
			}
			else
			{
				if (Root->parent != nullptr)
				{
					cout << Root->key << endl;
					Root = Root->parent;
				}
			}
		}
	}

琢磨了一天搞出来的,好麻烦。。。--,--
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值