您的位置:首页 > 编程语言 > C语言/C++

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

2015-06-11 13:13 489 查看
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;
}
}
}
}


琢磨了一天搞出来的,好麻烦。。。--,--
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息