二叉树的前序遍历后序遍历中序遍历的非递归实现以及相应的拓展
//树的后序遍历
void houxu(TreeNode* root)
{
int top = -1;
int flag[10000];
stack<TreeNode*> s_t;
TreeNode* p = root;
while (!s_t.empty() || p != NULL)
{
while (p != NULL)
{
++top;
s_t.push(p);
flag[top] = 0;
p = p->left;
}
//这里不需要的
while (top >= 0 && flag[top] == 1)//只有当右节点被访问到了才能访问根
{
--top;
cout << s_t.top()->val << endl;
s_t.pop();
}
if (!s_t.empty())
{
TreeNode* temp = s_t.top();
p = temp->right;
flag[top] = 1;
}
}
}
//树的中序遍历
void zhongxu(TreeNode* root)
{
TreeNode* p = root;
stack<TreeNode*> s_t;
while (!s_t.empty() || p != NULL)
{
while (p != NULL)
{
s_t.push(p);
p = p->left;
}
if (!s_t.empty())
{
TreeNode* temp = s_t.top();
cout << temp->val << endl;
p = temp->right;
s_t.pop();
}
}
}
//树的前序遍历
void qianxu(TreeNode* root)
{
TreeNode* p = root;
stack<TreeNode*> s_t;
while (!s_t.empty() || p != NULL)
{
while (p != NULL)
{
s_t.push(p);
cout << p->val << endl;
p = p->left;
}
if (!s_t.empty())
{
TreeNode* temp = s_t.top();
//cout << temp->val << endl;
p = temp->right;
s_t.pop();
}
}
}
一些拓展
求到目标节点的路径,输出的是从当前节点到根节点的路径,包含当前节点的
void houxu_tuozhan(TreeNode* root)
{
int top = -1;
int flag[10000];
stack<TreeNode*> s_t;
TreeNode* p = root;
while (!s_t.empty() || p != NULL)
{
while (p != NULL)
{
++top;
s_t.push(p);
flag[top] = 0;
p = p->left;
}
//这里不需要的
while (top >= 0 && flag[top] == 1)//只有当右节点被访问到了才能访问根
{
if (s_t.top()->val == 5)//如果相等的话就把 当前栈中的数据出去
{
while (!s_t.empty())
{
cout << s_t.top()->val << endl;
s_t.pop();
}
return;
}
--top;
s_t.pop();
}
if (!s_t.empty())
{
TreeNode* temp = s_t.top();
p = temp->right;
flag[top] = 1;
}
}
}
求两个在树上的节点的最近公共祖先(递归)
TreeNode* qiu_liangge(TreeNode* root,int target1,int target2)
{
//对于这种题目怎么计算因为:求两个存在在树中的节点最低公共祖先
TreeNode* p = root;
if (root == NULL)
return NULL;
if (root->val == target1)
return root;
if (root->val == target2)
return root;
TreeNode* left_1 = qiu_liangge(root->left, target1, target2);
TreeNode* right_1 = qiu_liangge(root->right, target1, target2);
if (left_1 == NULL&&right_1 == NULL)
return NULL;
if (left_1 != NULL&&right_1 != NULL)
return root;
if (left_1 == NULL)
return right_1;
if (right_1 == NULL)
return left_1;
}