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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cpp2088671660/article/details/46456383
	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;
				}
			}
		}
	}

琢磨了一天搞出来的,好麻烦。。。--,--

猜你喜欢

转载自blog.csdn.net/Cpp2088671660/article/details/46456383