树节点结构体:
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
};
递归建立二叉树:
TreeNode *createTree()
{
TreeNode *root;
int x;
scanf("%d", &x);
if (x == -1)
root = NULL;
else
{
root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = x;
root->left = createTree();
root->right = createTree();
}
return root;
}
递归先、中、后续:
void PreOrder(TreeNode *root)
{
if (root == 0)
return;
printf("%d", root->val);
PreOrder(root->left);
PreOrder(root->right);
}
void InOrder(TreeNode *root)
{
if (root == 0)
return;
InOrder(root->left);
printf("%d", root->val);
InOrder(root->right);
}
void PostOrder(TreeNode *root)
{
if (root == 0)
return;
PostOrder(root->left);
PostOrder(root->right);
printf("%d", root->val);
}
非递归先序:(借助stack)
void PreOrder_Nonrecursive(TreeNode *root)
{
if (root == 0)
return;
TreeNode *p = root;
stack<TreeNode *> S;
while (!s.empty() || p)
{
while (p)
{
cout << p->val << endl;
S.push(p);
p = p->left;
}
p = S.top();
S.pop();
p = p->right;
}
}
非递归中序:(借助stack,和先序区别在于:先序入栈时访问节点,中序出栈时访问节点)
void InOrder_Nonrecursive(TreeNode *root)
{
if (root == 0)
return;
TreeNode *p = root;
stack<TreeNode *> S;
while (!S.empty() || p)
{
while (p)
{
S.push(p);
p = p->left;
}
p = S.top();
S.pop();
cout << p->val << endl;
p = p->right;
}
}
非递归后续:(利用一个栈,精髓在于记录上一个访问节点,判断是否右孩子为空或为previsited)
void PostOrder_Nonrecursive1(TreeNode *root)
{
if (root == 0)
return;
TreeNode *p = root;
stack<TreeNode *> S;
TreeNode *previsited = NULL;
while (!S.empty() || p)
{
while (p)
{
S.push(p);
p = p->left;
}
p = S.top();
if (p->right == previsited || p->right == NULL)
{
cout << p->val << endl;
previsited = p;
S.pop();
p = NULL;
}
else
p = p->right;
}
}
接下来是巧妙地双栈后续:
void PostOrder_Dualstack(TreeNode *root)
{
if (root == 0)
return;
TreeNode *p = root;
stack<TreeNode *> S1;
stack<TreeNode *> S2;
S1.push(p);
while (!S1.empty())
{
p = S1.top();
S1.pop();
S2.push(p);
if (p->left) S1.push(p->left);
if (p->right) S2.push(p->right);
}
while (!S2.empty())
{
p = S2.top();
S2.pop();
cout << p->val << endl;
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
利用前、中序遍历确定二叉树:
TreeNode* create(int pre[], int in[], int l1,int r1, int l2, int r2)
{
if (l1 > r1) return NULL;
TreeNode *node = new TreeNode(pre[l1];
int l = l2;
int i = 0;
for (; l <= r2; l++, i++)
{
if (pre[l1] == in[l])
break;
}
node->left = create(pre, in, l1+1, l1+i, l2, l-1);
node->right = create(pre, in, l1+i+1, r1, l+1, r2);
return node;
}
文章借鉴自http://blog.csdn.net/hackbuteer1/article/details/6583988